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.

66 lines
1.9 KiB

#include "SudokuMatrix.h"
#include <stdio.h>
bool JudgeMatrix(SudokuMatrix* matrix){
printf("The original Sudoku matrix: \n");
PrintMatrix(matrix);
bool result = true;
// 检查每一行
// 原理: 用一个长度为9的数组记录每个数字出现的次数
// 如果某个数字出现了两次,那么这个数独矩阵就不符合要求
// 以下检查列和九宫格的原理相同。
for (int i=0;i<9;i++){
int row[9] = {0};
for (int j=0;j<9;j++){
row[matrix->matrix[i][j]-1]++;
}
for (int j=0;j<9;j++){
if (row[j] > 1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the row %d has been used!\n", j+1, i+1);
return false;
}
}
}
// 检查每一列
for (int i=0;i<9;i++){
int column[9] = {0};
for (int j=0;j<9;j++){
column[matrix->matrix[j][i]-1]++;
}
for (int j=0;j<9;j++){
if (column[j] > 1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the col %d has been used!\n", j+1, i+1);
return false;
}
}
}
// 检查每一个 3x3 的矩阵
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
int block[9] = {0};
for (int k=0;k<3;k++){
for (int l=0;l<3;l++){
block[matrix->matrix[i*3+k][j*3+l]-1]++;
}
}
for (int k=0;k<9;k++){
if (block[k] > 1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the block %d has been used!\n", k+1, i*3+j+1);
return false;
}
}
}
}
if (result){
printf("True:Valid initial Sudoku matrix!\n");
}
return result;
}