import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map seenInts = new HashMap<>(); // Populate matrix int[][] squareData = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int curr = scanner.nextInt(); squareData[i][j] = curr; } } Square square = new Square(squareData); System.out.println(square.getMinCost()); } } class Square { private static final int SQUARE_SIZE = 3; private int[][] square; public Square(int[][] square) { this.square = square; } public int getMinCost() { Square magicSquare = new Square(new int[][] { {4, 9, 2}, {3, 5, 7}, {8, 1, 6} }); int minCost = compare(magicSquare); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.flip(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); magicSquare.rotate(); minCost = Math.min(minCost, compare(magicSquare)); return minCost; } public int[][] getSquare() { return square; } public boolean isMagic() { return getMinCost() == 0; } public void print() { print(this); } private void print(Square square) { for (int i = 0; i < SQUARE_SIZE; i++) { for (int j = 0; j < SQUARE_SIZE; j++) { System.out.print(square.getSquare()[i][j] + " "); } System.out.println(); } } private void rotate() { int[][] rotatedSquare = new int[SQUARE_SIZE][SQUARE_SIZE]; for (int i = 0; i < SQUARE_SIZE; i++) { for (int j = 0; j < SQUARE_SIZE; j++) { rotatedSquare[j][Math.abs(SQUARE_SIZE - i - 1)] = square[i][j]; } } square = rotatedSquare; } private void flip() { int[][] flippedSquare = new int[SQUARE_SIZE][SQUARE_SIZE]; for (int i = 0; i < SQUARE_SIZE; i++) { for (int j = 0; j < SQUARE_SIZE; j++) { flippedSquare[j][Math.abs(SQUARE_SIZE - i - 1)] = square[j][i]; } } square = flippedSquare; } private int compare(Square inputSquare) { int cost = 0; for (int i = 0; i < SQUARE_SIZE; i++) { for (int j = 0; j < SQUARE_SIZE; j++) { cost += Math.abs(this.square[i][j] - inputSquare.getSquare()[i][j]); } } return cost; } }