import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static final int MAGIC_SUM = 15; public static List magicSquares = new ArrayList<>(); static { generateMagicSquares(); } public static int getAnswer(int number) { int answer = 99; if (magicSquares.contains(number)) { return 0; } for (int magicSquare : magicSquares) { int cost = 0; int testNumber = number; while (magicSquare > 0) { cost += Math.abs((testNumber % 10) - (magicSquare % 10)); testNumber /= 10; magicSquare /= 10; } if (cost < answer) { answer = cost; } } return answer; } public static void generateMagicSquares() { for (int a = 1 ; a <= 9 ; a++) { for (int b = 1 ; b <= 9 ; b++) { if (a == b) { continue; } for (int c = 1 ; c <= 9 ; c++) { if (a == c || b == c) { continue; } if (a + b + c == MAGIC_SUM) { for (int d = 1; d <= 9 ; d++) { if (a == d || b == d || c == d) { continue; } for (int e = 1 ; e <= 9 ; e++) { if (a == e || b == e || c == e || d == e) { continue; } for (int f = 1 ; f <= 9 ; f++) { if (a == f || b == f || c == f || d == f || e == f) { continue; } if (d + e + f == MAGIC_SUM) { for (int g = 1 ; g <= 9 ; g++) { if (a == g || b == g || c == g || d == g || e == g || f == g) { continue; } for (int h = 1 ; h <= 9 ; h++) { if (a == h || b == h || c == h || d == h || e == h || f == h || g == h) { continue; } for (int i = 1 ; i <= 9 ; i++) { if (a == i || b == i || c == i || d == i || e == i || f == i || g == i || h == i) { continue; } if (g + h + i == MAGIC_SUM) { if ((a + d + g == MAGIC_SUM) && (b + e + h == MAGIC_SUM) && (c + f + i == MAGIC_SUM)) { if ((a + e + i == MAGIC_SUM) && (g + e + c == MAGIC_SUM)) { magicSquares.add(a * 100_000_000 + b * 10_000_000 + c * 1_000_000 + d * 100_000 + e * 10_000 + f * 1_000 + g * 100 + h * 10 + i); } } } } } } } } } } } } } } } public static boolean isIntUnique(int number) { int holder = 0x1FF; // 1 1111 1111 while (number > 0) { int i = number % 10; holder = holder ^ (1 << (i - 1)); number = number / 10; } return (holder == 0); } public static String arrayToString(int[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0 ; i < array.length ; i++) { sb.append("" + array[i]); } return sb.toString(); } public static int[] stringToArray(String s) { int[] array = new int[s.length()]; for (int i = 0 ; i < s.length() ; i++) { array[i] = Integer.valueOf(s.charAt(i) + ""); } return array; } public static boolean hasUniqueValues(int[] matrix) { boolean hasUniqueValues = true; String sMatrix = arrayToString(matrix); if (sMatrix.matches(".*(.).*\\1.*")) { hasUniqueValues = false; } return hasUniqueValues; } public static void main(String[] args) { try (Scanner in = new Scanner(System.in);) { int num = 0; for (int i = 0 ; i < 9 ; i++) { int n = in.nextInt(); num += n * Math.pow(10, 8 - i); } System.out.println(getAnswer(num)); } } }