def squares = [] //https://en.wikipedia.org/wiki/Magic_square //Method_for_constructing_a_magic_square_of_order_3 // c is 5 so 0 < a < b < 5-a and b <> 2a // only a=1 and b=3 are good // count rotation and mirrors and we have these 8 // we can see than the corners are even squares << [[2,9,4],[7,5,3],[6,1,8]] squares << [[4,3,8],[9,5,1],[2,7,6]] squares << [[8,1,6],[3,5,7],[4,9,2]] squares << [[6,7,2],[1,5,9],[8,3,4]] squares << [[4,9,2],[3,5,7],[8,1,6]] squares << [[2,7,6],[9,5,1],[4,3,8]] squares << [[6,1,8],[7,5,3],[2,9,4]] squares << [[8,3,4],[1,5,9],[6,7,2]] Scanner sc = new Scanner(System.in) int[][] square = new int[3][3] for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ square[i][j] = sc.nextInt() } } int result = 0 result = Integer.MAX_VALUE squares.each{ int cost = 0 for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ cost += Math.abs(square[i][j]-it[i][j]) } } if(cost < result) result = cost; } println result