You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.3 KiB
94 lines
2.3 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
int check(int sudoku[9][9]) {
|
|
int w[9], c[9], b[9];
|
|
|
|
for (int i = 0; i < 9; i++) {
|
|
for (int j = 0; j < 9; j++) {
|
|
w[j] = 0;
|
|
c[j] = 0;
|
|
b[j] = 0;
|
|
}
|
|
|
|
for (int j = 0; j < 9; j++) {
|
|
int k = sudoku[i][j];
|
|
|
|
if (k == 0) continue;
|
|
if (w[k - 1] == 1) return 0;
|
|
w[k - 1] = 1;
|
|
|
|
k = sudoku[j][i];
|
|
|
|
if (k == 0) continue;
|
|
if (c[k - 1] == 1) return 0;
|
|
c[k - 1] = 1;
|
|
|
|
k = sudoku[(i / 3) * 3 + j / 3][(i % 3) * 3 + j % 3];
|
|
|
|
if (k == 0) continue;
|
|
if (b[k - 1] == 1) return 0;
|
|
b[k - 1] = 1;
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
int main() {
|
|
int a[9][9] = { 0 };
|
|
int i, j, k;
|
|
|
|
printf("The original Sudoku matrix:\n");
|
|
srand(time(NULL));
|
|
printf("|-------------------|\n");
|
|
|
|
for (i = 0; i < 9; i++) {
|
|
for (j = 0; j < 9; j++) {
|
|
if (j % 3 == 0) printf("|");
|
|
|
|
if (rand() % 3 == 0) {
|
|
do {
|
|
k = rand() % 9 + 1;
|
|
} while (a[i][k - 1] != 0);
|
|
|
|
a[i][k - 1] = k;
|
|
printf("%d", k);
|
|
}
|
|
else {
|
|
a[i][j] = 0;
|
|
printf(".");
|
|
}
|
|
|
|
if (j == 8) printf("|");
|
|
printf(" ");
|
|
}
|
|
|
|
if ((i + 1) % 3 == 0) printf("\n|-------------------|");
|
|
printf("\n");
|
|
}
|
|
|
|
if (check(a))
|
|
printf("True: Valid initial Sudoku matrix!\n");
|
|
else {
|
|
printf("False: Invalid initial Sudoku matrix!\n");
|
|
for (i = 0; i < 9; i++) {
|
|
for (j = i + 1; j < 9; j++) {
|
|
for (k = i / 3 * 3; k < i / 3 * 3 + 3; k++) {
|
|
for (int l = i % 3 * 3; l < i % 3 * 3 + 3; l++) {
|
|
if ((a[i][j] != 0 && a[i][j] == a[k][l]) ||
|
|
(a[j][i] != 0 && a[j][i] == a[l][k])) {
|
|
printf("The number %d in the row %d has been used!\n", a[i][j], i + 1);
|
|
goto end;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
end:;
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|