import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static ArrayList costArray = new ArrayList(); 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 scan = new Scanner(System.in); int[][] arr = new int[3][3]; for(int i = 0; i< 3; i++) { for(int j = 0; j < 3; j++) { arr[i][j] = scan.nextInt(); } } int[][] msquare1 = { {8,1,6}, {3,5,7}, {4,9,2} }; int[][] msquare2 = { {4,3,8}, {9,5,1}, {2,7,6} }; int[][] msquare3 = { {2,9,4}, {7,5,3}, {6,1,8} }; int[][] msquare4 = { {6,7,2}, {1,5,9}, {8,3,4} }; int[][] msquare5 = { {6,1,8}, {7,5,3}, {2,9,4} }; int[][] msquare6 = { {8,3,4}, {1,5,9}, {6,7,2} }; int[][] msquare7 = { {4,9,2}, {3,5,7}, {8,1,6} }; int[][] msquare8 = { {2,7,6}, {9,5,1}, {4,3,8} }; calculateMinCost(arr,msquare1); calculateMinCost(arr,msquare2); calculateMinCost(arr,msquare3); calculateMinCost(arr,msquare4); calculateMinCost(arr,msquare5); calculateMinCost(arr,msquare6); calculateMinCost(arr,msquare7); calculateMinCost(arr,msquare8); Collections.sort(costArray); System.out.println(costArray.get(0)); } static void calculateMinCost(int[][] arr, int[][] msquare) { int len = arr.length; int cost = 0; for(int i = 0; i < len; i++) { for(int j = 0; j < len; j++) { if(arr[i][j] != msquare[i][j]) { cost = cost + Math.abs(arr[i][j] - msquare[i][j]); } } } costArray.add(cost); } }