import sys def rotate_matrix(m): return [[m[0][2], m[1][2], m[2][2]], [m[0][1], m[1][1], m[2][1]], [m[0][0], m[1][0], m[2][0]]] def flip_matrix(m): return [[m[0][2], m[0][1], m[0][0]], [m[1][2], m[1][1], m[1][0]], [m[2][2], m[2][1], m[2][0]]] def diff_between_matrices(bad_m, magic_m): cost_counter = 0 # should probably use zip here for i, row in enumerate(bad_m): for j, value in enumerate(row): cost_counter += abs(value - magic_m[i][j]) return cost_counter def min_cost_matrix_permutations(matrix, new_matrix): costs = [] costs.append(diff_between_matrices(matrix, new_matrix)) for i in range(3): new_matrix = rotate_matrix(new_matrix) costs.append(diff_between_matrices(matrix, new_matrix)) new_matrix = flip_matrix(new_matrix) costs.append(diff_between_matrices(matrix, new_matrix)) for i in range(3): new_matrix = rotate_matrix(new_matrix) costs.append(diff_between_matrices(matrix, new_matrix)) return min(costs) matrix = [] for line in sys.stdin: row = [int(num.replace("\n", "")) for num in line.split(" ")] matrix.append(row) new_matrix = [[4, 9, 2], [3, 5, 7], [8, 1, 6]] cost = min_cost_matrix_permutations(matrix, new_matrix) print(cost)