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.
128 lines
3.0 KiB
128 lines
3.0 KiB
#include <stdio.h>
|
|
|
|
// 定义矩阵的大小
|
|
#define N 9
|
|
|
|
// 检查行是否满足数独条件
|
|
int isRowValid(int matrix[N][N], int row) {
|
|
int used[N + 1] = {0}; // 用于记录数字的使用情况
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
int num = matrix[row][i];
|
|
|
|
if (num != 0) {
|
|
if (used[num] == 1) {
|
|
printf("False: Invalid initial Sudoku matrix! The number %d in row %d has been used!\n", num, row + 1);
|
|
return 0;
|
|
}
|
|
used[num] = 1;
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
// 检查列是否满足数独条件
|
|
int isColValid(int matrix[N][N], int col) {
|
|
int used[N + 1] = {0}; // 用于记录数字的使用情况
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
int num = matrix[i][col];
|
|
|
|
if (num != 0) {
|
|
if (used[num] == 1) {
|
|
printf("False: Invalid initial Sudoku matrix! The number %d in column %d has been used!\n", num, col + 1);
|
|
return 0;
|
|
}
|
|
used[num] = 1;
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
// 检查一个3x3的小矩阵是否满足数独条件
|
|
int isBlockValid(int matrix[N][N], int startRow, int startCol) {
|
|
int used[N + 1] = {0}; // 用于记录数字的使用情况
|
|
|
|
for (int i = startRow; i < startRow + 3; i++) {
|
|
for (int j = startCol; j < startCol + 3; j++) {
|
|
int num = matrix[i][j];
|
|
|
|
if (num != 0) {
|
|
if (used[num] == 1) {
|
|
printf("False: Invalid initial Sudoku matrix! The number %d in block %d has been used!\n", num, (startRow / 3) * 3 + startCol / 3 + 1);
|
|
return 0;
|
|
}
|
|
used[num] = 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
// 主函数
|
|
int main() {
|
|
int sudoku[N][N] = {{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");
|
|
|
|
// 输出数独矩阵
|
|
for (int i = 0; i < N; i++) {
|
|
for (int j = 0; j < N; j++) {
|
|
printf("%d ", sudoku[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
int isValid = 1;
|
|
|
|
// 检查每一行
|
|
for (int i = 0; i < N; i++) {
|
|
if (!isRowValid(sudoku, i)) {
|
|
isValid = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// 检查每一列
|
|
if (isValid) {
|
|
for (int i = 0; i < N; i++) {
|
|
if (!isColValid(sudoku, i)) {
|
|
isValid = 0;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 检查每个3x3小矩阵
|
|
if (isValid) {
|
|
for (int i = 0; i < N; i += 3) {
|
|
for (int j = 0; j < N; j += 3) {
|
|
if (!isBlockValid(sudoku, i, j)) {
|
|
isValid = 0;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (isValid) {
|
|
printf("True: Valid initial Sudoku matrix!\n");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|