import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner stdin = new Scanner(System.in); int[] square = new int[9]; for (int i = 0; i <9; i++) { square[i] = stdin.nextInt(); } for (int i = 3; i <= 5; i++) { // Rearrange 3x3 matrix to spiral int temp = square[i]; switch (i) { case 3: square[i] = square[5]; square[5] = temp; break; case 4: square[i] = square[8]; square[8] = temp; break; case 5: square[i] = square[7]; square[7] = temp; break; } } int[] magic = {8, 1, 6, 7, 2, 9, 4, 3, 5}; // Known initial magic square defined in spiral int minCost = Integer.MAX_VALUE; for (int rot = 0; rot < 4; rot++) { int cost = computeCost(magic, square); if (cost < minCost) { minCost = cost; } cost = computeCost(reflectDiag(magic), square); if (cost < minCost) { minCost = cost; } magic = rotate90(magic); } System.out.println(minCost); } private static int[] rotate90(int[] square) { int n = square.length; int[] temp = new int[n]; if (n % 2 == 1) { temp[n-1] = square[n-1]; n-= 1; // Excludes central cell } for (int i = 0; i < n; i++) { temp[i] = square[(i+2) % n]; } return temp; } private static int[] reflectDiag(int[] square) { int n = square.length; int[] temp = new int[n]; for (int i = 0; i < n; i++) { int val = square[i]; switch (i) { case 5: temp[i] = square[3]; temp[3] = val; break; case 6: temp[i] = square[2]; temp[2] = val; break; case 7: temp[i] = square[1]; temp[1] = val; break; default: temp[i] = val; } } return temp; } private static int computeCost(int[] magic, int[] square) { int cost = 0; for (int i = 0; i < magic.length; i++) { cost+= Math.abs(magic[i]-square[i]); } return cost; } private static void printSq(int[] square) { for (int i = 0; i < square.length; i++) { System.out.println(square[i]); } } }