import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; class MagicSquare { private int[][] matrix; private int order; public MagicSquare(int order) { this.order = order; this.matrix = new int[order][order]; } public void fill() { for (int i = 1; i <= order; i++) { for (int j = 1; j <= order; j++) { matrix[i - 1][j - 1] = order * ((i + j - 1 + (int) Math.floor(order / 2)) % order) + ((i + 2 * j - 2) % order) + 1; } } } // 1 2 3 7 4 1 // 4 5 6 => 8 5 2 // 7 8 9 9 6 3 public void rotate() { int[][] rotatedMatrix = new int[order][order]; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { rotatedMatrix[i][j] = matrix[order - j - 1][i]; } } matrix = rotatedMatrix; } // 1 2 3 1 4 7 // 4 5 6 => 2 5 8 // 7 8 9 3 6 9 public void transpose() { int[][] transposedMatrix = new int[order][order]; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { transposedMatrix[i][j] = matrix[j][i]; } } matrix = transposedMatrix; } public int calculateScore(int[][] matrix) { int score = 0; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { score += Math.abs(matrix[i][j] - this.matrix[i][j]); } } return score; } public void print() { for (int row = 0; row < order; row++) { for (int col = 0; col < order; col++) { System.out.print(matrix[row][col] + " "); } System.out.println(); } } } public class Solution { static final int MAGIC_SQUARE_ORDER = 3; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[][] matrix = new int[MAGIC_SQUARE_ORDER][MAGIC_SQUARE_ORDER]; for (int i = 0; i < MAGIC_SQUARE_ORDER; i++) { for (int j = 0; j < MAGIC_SQUARE_ORDER; j++) { matrix[i][j] = scan.nextInt(); } } MagicSquare magicSquare = new MagicSquare(MAGIC_SQUARE_ORDER); magicSquare.fill(); int minScore = Integer.MAX_VALUE; for (int i = 0; i < 2; i++) { for (int j = 0; j < 4; j++) { minScore = Math.min(minScore, magicSquare.calculateScore(matrix)); magicSquare.rotate(); } magicSquare.transpose(); } System.out.println(minScore); } }