import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException{ /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); Solution sol = new Solution(); int[] mag = new int[9]; int n = 0; int k = 0; while (n < 3) { String[] l = bf.readLine().split(" "); for (int i =0; i < 3; i++) { mag[k++] = Integer.parseInt(l[i]); } n++; } System.out.println(sol.calculate(mag)); } private int calculate(int[]inp) { int[] arr = {1,2,3,4,5,6,7,8,9}; int min = 500; do { if (check(arr)) { min = Math.min(min, dif(arr, inp)); } } while (next(arr)); return min; } public boolean next(int[] perm) { int p = perm.length - 1; // 4 5 6 // 1 2 3 5 6 4 // 4 6 5 for (; p > 0 && perm[p -1] >= perm[p]; p--); if (p == 0) { return false; } int q = perm.length - 1; for (; q > 0 && perm[q] <= perm[p - 1]; q--); swap(perm, p-1, q); int l = p; int r = perm.length -1; while (l < r) { swap(perm, l, r); l++; r--; } return true; } private void swap(int[] perm, int l, int r) { int temp = perm[l]; perm[l] = perm[r]; perm[r] = temp; } private boolean check(int[] give) { int row1 = give[0] + give[1] + give[2]; int row2 = give[3] + give[4] + give[5]; int row3 = give[6] + give[7] + give[8]; int c1 = give[0] + give[3] + give[6]; int c2 = give[1] + give[4] + give[7]; int c3 = give[2] + give[5] + give[8]; int d1 = give[0] + give[4] + give[8]; int d2 = give[2] + give[4] + give[6]; if (row1 == 15 && row1 == row2 && row2 == row3 && row3 == c1 && c1 == c2 && c2 == c3 && d1 == d2 && d1 == 15) { return true; } return false; } private int dif(int[] give, int[] run) { int df = 0; for (int i = 0; i < 9; i++) { df += Math.abs(give[i] - run[i]); } return df; } private boolean canWePlace(int[][] runner, int r, int c, int n) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (runner[i][j] == n) { return false; } } } runner[r][c] = n; for (int [] row : runner) { if (checkRow(row)) { return false; } } runner[r][c] = 0; return true; } private boolean checkRow(int[] row) { if (row[0] != 0 && row[1] != 0 && row[2] != 0) { return row[0] + row[1] + row[2] != 15; } if (row[0] + row[1] + row[2] > 15) { return false; } return true; } }