import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int m[][] = new int[3][3]; for (int f = 0; f < 3; f++) { for (int c = 0; c < 3; c++) m[f][c] = s.nextInt(); } int mincost = 10000; for (int n1 = 9; n1 > 0; n1--) { for (int n2 = 9; n2 > 0; n2--) { // if (n2 == n1) // continue; int n3 = 15 - n1 - n2; // if ((n3 == n1) || n3 == n2) // continue; for (int n4 = 9; n4 > 0; n4--) { // if ((n4 == n1) || n4 == n2 || n4 == n3) // continue; int n5 = 15 - n4 - n3; // if ((n5 == n1) || n5 == n2 || n5 == n3||n5==n4) continue; int n6 = 15 - n2 - n4; int n7 = 15 - n6 - n1; int n8 = 15 - n1 - n5; int n9 = 15 - n2 - n8; int[][] matrix = new int[3][3]; matrix[0][0] = n2; matrix[0][1] = n8; matrix[0][2] = n9; matrix[1][0] = n6; matrix[1][1] = n1; matrix[1][2] = n7; matrix[2][0] = n4; matrix[2][1] = n5; matrix[2][2] = n3; if (isMagic(matrix)) { int cost = calcCost(matrix, m); if (cost < mincost) { mincost = cost; } } } } } System.out.println(mincost); } private static int calcCost(int[][] matrix, int[][] m) { int sum = 0; for (int f = 0; f < 3; f++) { for (int c = 0; c < 3; c++) { sum += Math.abs(matrix[f][c] - m[f][c]); } } return sum; } private static boolean isMagic(int matrix[][]) { for (int f = 0; f < 3; f++) { int sum = 0; for (int c = 0; c < 3; c++) { sum += matrix[f][c]; } if (sum != 15) { return false; } } for (int c = 0; c < 3; c++) { int sum = 0; for (int f = 0; f < 3; f++) { sum += matrix[f][c]; } if (sum != 15) { return false; } } int sum = 0; for (int c = 0; c < 3; c++) { sum += matrix[c][c]; } if (sum != 15) { return false; } sum = 0; for (int c = 0; c < 3; c++) { sum += matrix[c][2 - c]; } if (sum != 15) { return false; } for (int n = 1; n <= 9; n++) { boolean found = false; for (int f = 0; f < 3; f++) { for (int c = 0; c < 3; c++) { if (n == matrix[f][c]) found = true; } } if (!found) { return false; } } return true; } }