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.
lmk/实验三(有问题版本).c

120 lines
2.5 KiB

#include<stdio.h>
#include<string.h>
#include <time.h>
#include <stdlib.h>
void print(int board[9][9])/*打印的程序*/
{
int i,j;
printf("The original Sudoku matrix: \n");
printf("|-----------------------|");
printf("\n");
for(i=0;i<9;i++)
{
if(i==3)
{
printf("|-----------------------|");
printf("\n");
}
if(i==6)
{
printf("|-----------------------|");
printf("\n");
}
printf("| ");
for(j=0;j<9;j++)
{
if(j==3) printf("| ");
if(j==6) printf("| ");
printf("%d ",board[i][j]);
}
printf("|");
printf("\n");
}
printf("|-----------------------|\n");
}
void test(int board[9][9])/*测试是否为数独矩阵*/
{
int num[10]={0};
int k=0;
int i=0,j=0;
int a=0,b=0;
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)/*验证行*/
{
if(board[i][j]!=0&&num[board[i][j]]==0)
num[board[i][j]]++;
else if(board[i][j]!=0&&num[board[i][j]]!=0)
{
k++;
printf("False:Invalid initial Sudoku matrix!\n");
printf(" The number %d in the col %d has been used!",board[i][j],i);
}
}
for(i=0;i<10;i++)
num[i]=0;
}
if(k==0)/*防止输出两次错误*/
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)/*验证列*/
{
if(board[j][i]!=0&&num[board[j][i]]==0)
num[board[j][i]]++;
else if(board[j][i]!=0&&num[board[j][i]]!=0)
{
k++;
printf("False:Invalid initial Sudoku matrix!\n");
printf(" The number %d in the row %d has been used!",board[j][i],i);
}
}
for(i=0;i<10;i++)
num[i]=0;
}
}
if(k==0)/*防止输出两次错误*//*验证矩阵块*/
{
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
for(a=(i-1)*3;a<=i*3-1;a++)
{
for(b=(j-1)*3;b<=j*3-1;b++)
{
if(board[a][b]!=0&&num[board[a][b]]==0)
num[board[a][b]]++;
else if(board[a][b]!=0&&num[board[a][b]]!=0)
{
k++;
printf("False:Invalid initial Sudoku matrix!\n");
printf(" The number %d in the block %d has been used!",board[a][b],i*j);
}
}
}
for(i=0;i<10;i++)
num[i]=0;
}
}
}
if(k==0)/*最后输出正确*/
printf("True:Valid initial Sudoku matrix!");
}
int main()
{
int board[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}};
print(board);
test(board);
return 0;
}