import itertools def sum_diag(square, primary=True): n = len(square) if primary: return sum([square[x][x] for x in range(n)]) else: return sum([square[row][n - row - 1] for row in range(n)]) def transpose(square): n = len(square) return [[square[j][i] for j in range(n)] for i in range(n)] def is_magic(square): n = len(square) sumValue = 0 for i,row in enumerate(square): if i == 0: sumValue = sum(row) else: if(sum(row) != sumValue): return False for col in transpose(square): if sum(col) != sumValue: return False if sum_diag(square) != sumValue: return False if sum_diag(square, primary=False) != sumValue: return False return True def magic_permutaions(): perms = itertools.permutations(range(1, 10)) perms = [list(case) for case in perms] perms = [[case[0:3], case[3:6], case[6:9]] for case in perms] perms = [case for case in perms if is_magic(case)] return perms def cost(fromMat, toMat): n = len(fromMat) return sum([abs(fromMat[i][j] - toMat[i][j]) for i in range(n) for j in range(n)]) if __name__ == "__main__": matrix = [] for i in range(3): matrix.append([int(x) for x in input().split(' ')]) minimum = min([cost(matrix, perm) for perm in magic_permutaions()]) print(minimum)