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.

93 lines
3.1 KiB

#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
void print_sudoku(int matrix[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%d ", matrix[i][j]);
if ((j + 1) % 3 == 0 && j != 8) {
printf("| ");
}
}
printf("\n");
if ((i + 1) % 3 == 0 && i != 8) {
printf("------+-------+------\n");
}
}
}
bool is_valid_sudoku(int matrix[SIZE][SIZE]) {
// 检查行、列和 3x3 小块
for (int i = 0; i < SIZE; i++) {
bool row_check[SIZE + 1] = { false }; // 用于检查行中 1-9 的出现情况
bool col_check[SIZE + 1] = { false }; // 用于检查列中 1-9 的出现情况
for (int j = 0; j < SIZE; j++) {
// 检查行
if (matrix[i][j] != 0) {
if (row_check[matrix[i][j]]) {
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the row %d has been used!\n", matrix[i][j], i + 1);
return false;
}
row_check[matrix[i][j]] = true;
}
// 检查列
if (matrix[j][i] != 0) {
if (col_check[matrix[j][i]]) {
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the col %d has been used!\n", matrix[j][i], i + 1);
return false;
}
col_check[matrix[j][i]] = true;
}
}
}
// 检查 3x3 小块
for (int start_row = 0; start_row < SIZE; start_row += 3) {
for (int start_col = 0; start_col < SIZE; start_col += 3) {
bool block_check[SIZE + 1] = { false }; // 用于检查 3x3 小块
for (int i = start_row; i < start_row + 3; i++) {
for (int j = start_col; j < start_col + 3; j++) {
if (matrix[i][j] != 0) {
if (block_check[matrix[i][j]]) {
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the block %d has been used!\n", matrix[i][j], (start_row / 3) * 3 + (start_col / 3) + 1);
return false;
}
block_check[matrix[i][j]] = true;
}
}
}
}
}
return true;
}
int main() {
// 示例数独矩阵,可以根据需要修改
int sudoku_matrix[SIZE][SIZE] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
printf("The original Sudoku matrix:\n");
print_sudoku(sudoku_matrix);
if (is_valid_sudoku(sudoku_matrix)) {
printf("True:Valid initial Sudoku matrix!\n");
}
return 0;
}