#include #include #include #include #include int is_magic(int matrix[3][3]) { int x1 = matrix[0][0] + matrix[0][1] + matrix[0][2]; int x2 = matrix[1][0] + matrix[1][1] + matrix[1][2]; if (x1 != x2) return 0; int x3 = matrix[2][0] + matrix[2][1] + matrix[2][2]; if (x2 != x3) return 0; int y1 = matrix[0][0] + matrix[0][1] + matrix[0][2]; if (x3 != y1) return 0; int y2 = matrix[1][0] + matrix[1][1] + matrix[1][2]; if (y1 != y2) return 0; int y3 = matrix[2][0] + matrix[2][1] + matrix[2][2]; if (y2 != y3) return 0; int d1 = matrix[0][0] + matrix[1][1] + matrix[2][2]; if (y3 != d1) return 0; int d2 = matrix[2][0] + matrix[1][1] + matrix[0][2]; if (d1 != d2) return 0; if (d2 != 15) return 0; return 1; } int magic_squares[8][3][3] = { { {8, 1, 6}, {3, 5, 7}, {4, 9, 2} }, { {4, 3, 8}, {9, 5, 1}, {2, 7, 6} }, { {2, 9, 4}, {7, 5, 3}, {6, 1, 8} }, { {6, 7, 2}, {1, 5, 9}, {8, 3, 4} }, { {6, 1, 8}, {7, 5, 3}, {2, 9, 4} }, { {8, 3, 4}, {1, 5, 9}, {6, 7, 2} }, { {4, 9, 2}, {3, 5, 7}, {8, 1, 6} }, { {2, 7, 6}, {9, 5, 1}, {4, 3, 8} } }; int calculate_cost(int a[3][3], int b[3][3]) { int cost = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cost += abs(a[i][j] - b[i][j]); } } return cost; } int main() { int matrix[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scanf("%d", (matrix[i] + j)); } } int min_cost = INT_MAX; for (int i = 0; i < 8; i++) { int cost = calculate_cost(matrix, magic_squares[i]); if (cost < min_cost) { min_cost = cost; } } printf("%d", min_cost); return 0; }