import static java.lang.Integer.min; import static java.lang.Math.abs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; public class MagicNums { private static List correct = new ArrayList<>(); private static final int MAX = 9; private static int[] nums = new int[MAX]; private static final int[][] valid = { {2, 7, 6, 9, 5, 1, 4, 3, 8}, {2, 9, 4, 7, 5, 3, 6, 1, 8}, {4, 3, 8, 9, 5, 1, 2, 7, 6}, {4, 9, 2, 3, 5, 7, 8, 1, 6}, {6, 1, 8, 7, 5, 3, 2, 9, 4}, {6, 7, 2, 1, 5, 9, 8, 3, 4}, {8, 1, 6, 3, 5, 7, 4, 9, 2}, {8, 3, 4, 1, 5, 9, 6, 7, 2}, }; private static void generate(int lev) { if (lev == MAX) { if (isOK()) { correct.add( nums ); System.out.println(Arrays.toString(nums).replace( '[', '{').replace( "]", "},")); } } else { for (int i = 1; i < 10; i++) { nums[lev] = i; generate( lev + 1 ); } } } private static boolean isOK() { HashSet sumsSet = new HashSet<>(); HashSet digs = new HashSet<>(); //int[][] sums = new int[4][3]; int[] sums = new int[8]; for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { int v = nums[r * 3 + c]; digs.add(v); sums[r] += v; sums[3 + c] += v; if (r == c) sums[6] += v; if (2 - c == r) sums[7] += v; } } //Arrays.stream( sums ).map( v -> v ).collect( Collectors.toSet() ); // if (digs.size() == 1) { // System.out.println(Arrays.toString(nums)); // System.out.println(Arrays.toString(sums)); // System.out.println(); // } for (int s : sums) { sumsSet.add(s); } return digs.size() == 9 && sumsSet.size() == 1; } private static int calcDiff(int idx) { int diff = 0; for (int i = 0; i < MAX; i++) { diff += abs(nums[i] - valid[idx][i]); } return diff; } public static void main(String[] args) { //generate(0); //correct.stream().forEach( nn -> System.out.println(Arrays.toString(nn).replace( '[', '{').replace( "]", "},")) ); //System.out.println(correct.size()); Scanner in = new Scanner(System.in); for (int i = 0; i < MAX; i++) { nums[i] = in.nextInt(); } int diff = Integer.MAX_VALUE; for (int i = 0; i < valid.length; i++) { diff = min(diff, calcDiff(i)); } System.out.println(diff); } }