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.3 KiB
115 lines
3.3 KiB
#include <stdio.h>
|
|
#include <stdbool.h>
|
|
|
|
void printMatrix(int matrix[9][9]) {
|
|
for (int i = 0; i < 9; i++) {
|
|
if (i == 0 || i == 3 || i == 6) {
|
|
printf("|-----------------------|\n");
|
|
}
|
|
for (int j = 0; j < 9; j++) {
|
|
if (j == 0 || j == 3 || j == 6) {
|
|
printf("| ");
|
|
}
|
|
if (matrix[i][j] == 0) {
|
|
printf(". ");
|
|
}
|
|
else {
|
|
printf("%d ", matrix[i][j]);
|
|
}
|
|
printf("|\n");
|
|
}
|
|
printf("|-----------------------|\n");
|
|
}
|
|
}
|
|
|
|
// 检查行中数字1 - 9是否最多出现一次
|
|
bool checkRows(int matrix[9][9]) {
|
|
for (int i = 0; i < 9; i++) {
|
|
int count[9] = {0};
|
|
for (int j = 0; j < 9; j++) {
|
|
if (matrix[i][j] > 0 && matrix[i][j] <= 9) {
|
|
int num = matrix[i][j] - 1;
|
|
if (count[num] > 0) {
|
|
return false;
|
|
}
|
|
count[num]++;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// 检查列中数字1 - 9是否最多出现一次
|
|
bool checkColumns(int matrix[9][9]) {
|
|
for (int j = 0; j < 9; j++) {
|
|
int count[9] = {0};
|
|
for (int i = 0; i < 9; i++) {
|
|
if (matrix[i][j] > 0 && matrix[i][j] <= 9) {
|
|
int num = matrix[i][j] - 1;
|
|
if (count[num] > 0) {
|
|
printf("The number %d in the col %d has been used!\n", matrix[i][j], j);
|
|
return false;
|
|
}
|
|
count[num]++;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// 检查3x3子矩阵中数字1 - 9是否最多出现一次
|
|
bool checkSubMatrices(int matrix[9][9]) {
|
|
for (int row = 0; row < 9; row += 3) {
|
|
for (int col = 0; col < 9; col += 3) {
|
|
int count[9] = {0};
|
|
for (int i = row; i < row + 3; i++) {
|
|
for (int j = col; j < col + 3; j++) {
|
|
if (matrix[i][j] > 0 && matrix[i][j] <= 9) {
|
|
int num = matrix[i][j] - 1;
|
|
if (count[num] > 0) {
|
|
printf("The number %d in the block %d has been used!\n", matrix[i][j], (row / 3) * 3 + col / 3);
|
|
return false;
|
|
}
|
|
count[num]++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// 判断矩阵是否满足数独矩阵的定义
|
|
bool isSudokuMatrix(int matrix[9][9]) {
|
|
if (!checkRows(matrix)) {
|
|
return false;
|
|
}
|
|
if (!checkColumns(matrix)) {
|
|
return false;
|
|
}
|
|
return checkSubMatrices(matrix);
|
|
}
|
|
|
|
int main() {
|
|
printf("The original Sudoku matrix: \n");
|
|
int matrix[9][9] = {
|
|
{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}
|
|
};
|
|
printMatrix(matrix);
|
|
bool result = isSudokuMatrix(matrix);
|
|
if (result) {
|
|
printf("True:Valid initial Sudoku matrix!\n");
|
|
} else {
|
|
printf("False:Invalid initial Sudoku matrix!\n");
|
|
}
|
|
return 0;
|
|
}
|