import java.io.*; import java.util.*; public class Solution { public static int get(int[] table, int row, int col) { return table[row*3 + col]; } public static void set(int[] table, int row, int col, int value) { table[row*3 + col] = value; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] table = new int[9]; for (int i = 0; i < 9; i++) { table[i] = scanner.nextInt(); } List magicSquares = allSquares(); int min = Integer.MAX_VALUE; int[] argmin = null; for (int[] magicSquare : magicSquares) { int delta = delta(table, magicSquare, min); if (delta < min) { argmin = magicSquare; min = delta; } } System.out.println(min); } public static List allSquares() { return allSquares(new int[9], 0, new boolean[10]); } public static int delta(int[] table, int[] table2, int min) { int result = 0; for (int i = 0; i < 9; i++) { result += Math.abs(table[i]-table2[i]); } return result; } public static List allSquares(int[] current, int pos, boolean[] taken) { if (pos == 9) { return Collections.singletonList(current); } List result = new ArrayList<>(); if (pos == 2) { int expected = 15 - get(current, 0, 0) - get(current, 0, 1); if (expected >= 1 && expected <= 9 && !taken[expected]) { result.addAll(sqs(current, pos, taken, expected)); } } else if (pos == 5) { int expected = 15 - get(current, 1, 0) - get(current, 1, 1); if (expected >= 1 && expected <= 9 && !taken[expected]) { result.addAll(sqs(current, pos, taken, expected)); } } else if (pos == 6) { int expected1 = 15 - get(current, 0, 0) - get(current, 1, 0); int expected2 = 15 - get(current, 1, 1) - get(current, 0, 2); if (expected1 == expected2 && expected1 >= 1 && expected1 <= 9 && !taken[expected1]) { result.addAll(sqs(current, pos, taken, expected1)); } } else if (pos == 7) { int expected = 15 - get(current, 0, 1) - get(current, 1, 1); if (expected >= 1 && expected <= 9 && !taken[expected]) { result.addAll(sqs(current, pos, taken, expected)); } } else if (pos == 8) { int expected1 = 15 - get(current, 0, 2) - get(current, 1, 2); int expected2 = 15 - get(current, 0, 0) - get(current, 1, 1); int expected3 = 15 - get(current, 2, 0) - get(current, 2, 1); if (expected1 == expected2 && expected1 == expected3 && expected1 >= 1 && expected1 <= 9 && !taken[expected1]) { result.addAll(sqs(current, pos, taken, expected1)); } } else { for (int i = 1; i <= 9; i++) { if (!taken[i]) { result.addAll(sqs(current, pos, taken, i)); } } } return result; } public static List sqs(int[] current, int pos, boolean[] taken, int number) { int[] copy = Arrays.copyOf(current, 9); copy[pos] = number; boolean[] takenCopy = Arrays.copyOf(taken, 10); takenCopy[number] = true; return allSquares(copy, pos + 1, takenCopy); } }