# Enter your code here. Read input from STDIN. Print output to STDOUT all_magic_squares = [] a = [[4, 9, 2], [3, 5, 7], [8, 1, 6]] # From example. all_magic_squares.append(a) # Rotate each magic square 90 degrees. for i in range(3): a = zip(*a[::-1]) a = map(list, a) all_magic_squares.append(a) # Reflect all magic squares by swapping # the "first" and "last" columns. reflected_squares = [[n[2], n[1], n[0]] for n in all_magic_squares] # Extend/combine the original list with the reflections. all_magic_squares.extend(reflected_squares) # At this point, I have all mathematical configs for order 3 magic squares. # I just need to compare each test square against this list and see which # has the lowest total sum needed to "morph" to magic. sums = [] test_square = [] for i in range(3): s = map(int,raw_input().strip().split(' ')) test_square.append(s) flat_input = [i for j in test_square for i in j] sums = [] for sq in all_magic_squares: flat_sq = [i for j in sq for i in j] diffs = [abs(x[0] - x[1]) for x in zip(flat_sq, flat_input)] sums.append(sum(diffs)) print min(sums)