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.

115 lines
3.4 KiB

#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool isValidSudoku(int grid[SIZE][SIZE]);
void findInvalidReason(int grid[SIZE][SIZE]);
void print(int matrix[9][9]);
int main() {
int sudoku[SIZE][SIZE] = { {8, 3, 0, 0, 5, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 9, 0, 4, 0},
{0, 0, 6, 0, 0, 0, 7, 0, 2},
{3, 0, 0, 2, 4, 0, 0, 0, 0},
{0, 0, 0, 6, 1, 9, 5, 0, 0},
{0, 0, 0, 8, 1, 7, 0, 0, 6},
{0, 0, 0, 6, 2, 0, 0, 7, 0},
{0, 9, 4, 0, 0, 5, 0, 0, 0},
{0, 8, 0, 3, 8, 0, 1, 0, 0}};
printf("The original Sudoku matrix: \n");
print(sudoku);
if (isValidSudoku(sudoku)) {
printf("True:Valid initial Sudoku matrix!\n");
} else {
printf("False:Invalid initial Sudoku matrix!\n");
findInvalidReason(sudoku);
}
return 0;
}
void printSudoku(int grid[SIZE][SIZE]) {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%2d ", grid[i][j]);
if (j % 3 == 2) printf("|");
}
printf("\n");
if (i % 3 == 2) {
printf("---------------------\n");
}
}
}
bool isValidSudoku(int grid[SIZE][SIZE]) {
int rows[SIZE][SIZE] = {0}, cols[SIZE][SIZE] = {0}, boxes[SIZE][SIZE] = {0};
int i, j, num;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (grid[i][j] != 0) {
num = grid[i][j] - 1;
if (++rows[i][num] > 1 || ++cols[j][num] > 1 || ++boxes[i / 3 * 3 + j / 3][num] > 1) {
return false;
}
}
}
}
return true;
}
void findInvalidReason(int grid[SIZE][SIZE]) {
int rows[SIZE][SIZE] = {0}, cols[SIZE][SIZE] = {0}, boxes[SIZE][SIZE] = {0};
int i, j, num;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (grid[i][j] != 0) {
num = grid[i][j] - 1;
rows[i][num]++;
cols[j][num]++;
boxes[i / 3 * 3 + j / 3][num]++;
}
}
}
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (grid[i][j] != 0) {
num = grid[i][j] - 1;
if (rows[i][num] > 1) {
printf("The number %d in the row %d has been used!\n", grid[i][j], i + 1);
return;
} else if (cols[j][num] > 1) {
printf("The number %d in the col %d has been used!\n", grid[i][j], j + 1);
return;
} else if (boxes[i / 3 * 3 + j / 3][num] > 1) {
printf("The number %d in the block %d has been used!\n", grid[i][j], (i / 3) * 3 + (j / 3) + 1);
return;
}
}
}
}
}
//<2F><>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
void print(int matrix[9][9]) {
int i, j;
printf("|-----------------------------|\n");
for (i = 0; i < SIZE; i++) {
printf("|");
for (j = 0; j < SIZE; j++) {
printf("%2d ", matrix[i][j]);
if ((j + 1) % 3 == 0) printf("|");
}
printf("\n");
if ((i + 1) % 3 == 0 && i < 8) {
printf("|-----------------------------|\n"); }
}
printf("|-----------------------------|\n");
}