import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { int[][][] solutions = {{{8,1,6},{3,5,7},{4,9,2}}, {{4,9,2},{3,5,7},{8,1,6}}, {{4,3,8},{9,5,1},{2,7,6}}, {{2,7,6},{9,5,1},{4,3,8}}, {{2,9,4},{7,5,3},{6,1,8}}, {{6,1,8},{7,5,3},{2,9,4}}, {{6,7,2},{1,5,9},{8,3,4}}, {{8,3,4},{1,5,9},{6,7,2}}}; /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); int[][] matrix = new int[3][3]; /* Parse input */ for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matrix[i][j] = in.nextInt(); } } /* Close scanner */ in.close(); /* Check cost to convert matrix to magic square by comparing to solutions */ int[] costs = new int[8]; for (int i = 0; i < 8; i++) { int currentCost = 0; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { currentCost += Math.abs(solutions[i][row][col]-matrix[row][col]); } } costs[i] = currentCost; } /* Sort costs from smallest to largest then print out smallest (i.e. 1st element in array) */ Arrays.sort(costs); System.out.println(costs[0]); } }