ADD file via upload

main
pcshlj3an 2 weeks ago
parent efca61f9f1
commit 39bfd481c4

@ -0,0 +1,103 @@
#include <stdio.h>
#define SIZE 9
void printSudoku(int board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (j % 3 == 0 && j != 0) {
printf("| ");
}
if (board[i][j] == 0) {
printf(". "); // 用'.'表示空白
}
else {
printf("%d ", board[i][j]);
}
}
printf("\n");
if ((i + 1) % 3 == 0 && i != 8) {
printf("---------------------\n");
}
}
}
int isValidSudoku(int board[SIZE][SIZE]) {
int row[SIZE][SIZE] = { 0 }; // 行使用情况
int col[SIZE][SIZE] = { 0 }; // 列使用情况
int block[SIZE][SIZE] = { 0 }; // 3x3块使用情况
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
int num = board[i][j];
if (num != 0) {
int blockIndex = (i / 3) * 3 + (j / 3);
// 检查行
if (row[i][num - 1]) {
printf("False: Invalid initial Sudoku matrix!\n");
printf("The number %d in the row %d has been used!\n", num, i + 1);
return 0; // 行重复,返回不合法
}
row[i][num - 1] = 1; // 标记该数字在行中使用过
// 检查列
if (col[j][num - 1]) {
printf("False: Invalid initial Sudoku matrix!\n");
printf("The number %d in the col %d has been used!\n", num, j + 1);
return 0; // 列重复,返回不合法
}
col[j][num - 1] = 1; // 标记该数字在列中使用过
// 检查3x3块
if (block[blockIndex][num - 1]) {
printf("False: Invalid initial Sudoku matrix!\n");
printf("The number %d in the block %d has been used!\n", num, blockIndex + 1);
return 0; // 块重复,返回不合法
}
block[blockIndex][num - 1] = 1; // 标记该数字在块中使用过
}
}
}
return 1; // 如果没有问题,返回合法
}
int main() {
int board0[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}
};
int board1[SIZE][SIZE] = {
{8, 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");
printSudoku(board0);
if (isValidSudoku(board0)) {
printf("True: Valid initial Sudoku matrix!\n");
}
printf("\nThe original Sudoku matrix:\n");
printSudoku(board1);
if (isValidSudoku(board1)) {
printf("True: Valid initial Sudoku matrix!\n");
}
return 0;
}
Loading…
Cancel
Save