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.

120 lines
2.7 KiB

#include <stdio.h>
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ĸ<EFBFBD>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
void printarr(int arr[9][9])
{
int i,j,k,n;
for(n=0;n<=6;n=n+3)
{
printf("|-----------------------|\n") ;
for(i=n;i<=n+2;i++)
{
for(k=0;k<=6;k=k+3)
{
printf("|");
for(j=k;j<=k+2;j++)
{
printf(" %d",arr[i][j]);
}
printf(" ");
}
printf("|\n");
}
}
printf("|-----------------------|\n") ;
}
const char* checkSudoku(int matrix[9][9])
{
// <20><><EFBFBD><EFBFBD>ÿһ<C3BF><D2BB>
for (int i = 0; i < 9; i++)
{
int seen[10] = {0};
for (int j = 0; j < 9; j++)
{
int num = matrix[i][j];
if (num != 0)
{
if (seen[num] != 0)
{
printf("False:Invalid initial Sudoku matrix!\nThe number %d in the row %d has been used!",num,i+1);
return 0;
}
seen[num] = 1;
}
}
}
// <20><><EFBFBD><EFBFBD>ÿһ<C3BF><D2BB>
for (int j = 0; j < 9; j++)
{
int seen[10] = {0};
for (int i = 0; i < 9; i++)
{
int num = matrix[i][j];
if (num != 0)
{
if (seen[num] != 0)
{
printf("False:Invalid initial Sudoku matrix!\nThe number %d in the col %d has been used!",num,j+1);
return 0;
}
seen[num] = 1;
}
}
}
// <20><><EFBFBD><EFBFBD>ÿ<EFBFBD><C3BF> 3x3 <20>Ӿ<EFBFBD><D3BE><EFBFBD>
for (int block = 0; block < 9; block++)
{
int seen[10] = {0};
int startRow = (block / 3) * 3;
int startCol = (block % 3) * 3;
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 (seen[num] != 0)
{
printf("False:Invalid initial Sudoku matrix!\nThe number %d in the block %d has been used!",num,block+1);
return 0;
}
seen[num] = 1;
}
}
}
}
return "True:Valid initial Sudoku matrix!";
}
int main() {
int sudokuMatrix[9][9] = {
{3, 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}
};
// <20><><EFBFBD><EFBFBD>ԭʼ<D4AD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
printf("The original Sudoku matrix: \n");
printarr(sudokuMatrix);
// <20>ж<EFBFBD><D0B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7>Ϸ<EFBFBD>
const char* result = checkSudoku(sudokuMatrix);
printf("%s\n", result);
return 0;
}