#include #include #include /* * 1 6 8 * 5 7 3 * 9 2 4 * */ int msq[3][3]; int val[3][3]; int min_diff = INT_MAX; #define MIND(a,b) (a) < (b) ? (a) : (b) int is_valid(int i, int j, int num) { int p, q, sum = 0; /* check duplicate */ for (p = 0; p < 3; p++) { for (q = 0; q < 3; q++) { if (!(p == i && q == j)) if (msq[p][q] == num) return 0; } } sum = num; for (p = 0; p < 3; p++) { if ( msq[p][j] != 0) { sum += msq[p][j]; } else { if (p != i) break; } } if (p == 3 && sum != 15) return 0; sum = num; for (q = 0; q < 3; q++) { if (msq[i][q] != 0) { sum += msq[i][q]; } else { if (q != j) break; } } if (q == 3 && sum != 15) { return 0; } if (i == j) { sum = num; for (p = 0; p < 3; p++) { if (msq[p][p] != 0) { sum += msq[p][p]; } else { if (p != i) break; } } if (p == 3 && sum != 15) return 0; } if (abs(i - j) == 2) { sum = num; for (p = 0; p < 3; p++) { if (msq[p][2-p] != 0) { sum += msq[p][2-p]; } else { if (p != i) break; } } if (p == 3 && sum != 15) return 0; } return 1; } void reset_msq() { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { msq[i][j] = 0; } } } int print_msq() { int i, j; printf ("\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf ("%d ", msq[i][j]); } printf ("\n"); } return 0; } int mdiff() { int diff = 0; int i,j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { diff += abs(val[i][j] - msq[i][j]); } } return diff; } void updatediff() { int diff; diff = mdiff(); min_diff = MIND(min_diff, diff); } int is_msq(int i, int j) { int p, q, k; if (j == 3) return 1; if (msq[i][j] != 0) { if (i == 2) { p = 0; q = j+1; } else { p = i+1; q = j; } return is_msq(p, q); } for (k = 1; k < 10; k++) { if (is_valid(i, j, k)) { msq[i][j] = k; if (i == 2) { p = 0; q = j+1; } else { p = i+1; q = j; } if (is_msq(p, q)) { //print_msq(); updatediff(); } msq[i][j] = 0; } } return 0; } int main() { int k; scanf("%d %d %d", &val[0][0], &val[0][1], &val[0][2]); scanf("%d %d %d", &val[1][0], &val[1][1], &val[1][2]); scanf("%d %d %d", &val[2][0], &val[2][1], &val[2][2]); for (k = 1; k < 10; k++) { msq[0][0] = k; if (is_msq(0, 0)) { //print_msq(); } reset_msq(); } printf ("%d \n", min_diff); return 0; }