From d758f2f6d9806f91b2e91b9e5eff4b5bca729f45 Mon Sep 17 00:00:00 2001 From: pcn3xiqjt <2556107223@qq.com> Date: Tue, 31 Oct 2023 09:39:28 +0800 Subject: [PATCH] ADD file via upload --- 4补充矩阵.c | 116 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 4补充矩阵.c diff --git a/4补充矩阵.c b/4补充矩阵.c new file mode 100644 index 0000000..e925f14 --- /dev/null +++ b/4补充矩阵.c @@ -0,0 +1,116 @@ +#include +int correct(int board[9][9]){ + int col[9]={0},row[9]={0},block[9]={0}; + int i,j; + for(i=0;i<9;++i){ + for(j=0;j<9;j++){ + int index=1<<(board[i][j]-1); + int blockindex=i/3*3+j/3; + if(board[i][j]!=0){ + if(row[i]&index){ + printf("False:Invalid initial Sudoku matrix!\n"); + printf("The number %d in the row %d has been used!",board[i][j],i+1); + return 0; + } + row[i]=index; + if(col[j]&index){ + printf("False:Invalid initial Sudoku matrix!\n"); + printf("The number %d in the rol %d has been used!",board[i][j],j+1); + return 0; + } + col[j]=index; + if(block[blockindex]&index){ + printf("False:Invalid initial Sudoku matrix!\n"); + printf("The number %d in the block %d has been used!",board[i][j],blockindex+1); + return 0; + } + block[blockindex]=index; + } + + + + } + } + printf("True:Valid initial Sudoku matrix!\n"); + return 1; + +} +int isSafe(int board[9][9], int row, int col, int num) { + int x,i,j; + for (x = 0; x <= 8; x++) + if (board[row][x] == num) + return 0; + for (x = 0; x <= 8; x++) + if (board[x][col] == num) + return 0; + int sRow = row - row % 3, sCol = col - col % 3; + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + if (board[i + sRow][j + sCol] == num) + return 0; + return 1; +} +int solve(int board[9][9]){ + int num; + int i=0,j=0; + for(i=0;i<9;i++){ + for(j=0;j<9;j++){ + if(board[i][j]==0){ + for(num=1;num<=9;++num){ + if(isSafe(board,i,j,num)){ + board[i][j]=num; + if(solve(board)){ + return 1; + } + board[i][j]=0; + } + + } + return 0; + } + } + } + return 1; +} +void print(int board[9][9]){ + printf("|---|---|---|---|---|---|\n"); + int i=0,j=0,s=0,k=0; + for(i=0;i<9;++i){ + for(j=0;j<9;j++){ + while(j%3==0){ + printf("| "); + break; + } + printf("%d ",board[i][j]); + } + printf("|\n"); + while((i+1)%3==0){ + printf("|---|---|---|---|---|---|\n"); + break; + } + } +} +int main(){ + int board1[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}}; + printf("The original Sudoku matrix:\n"); + print(board1); + if(correct(board1)){ + if(solve(board1)){ + printf("The solution of Sudoku matrix:\n"); + print(board1); + }else{ + printf("No solutions!\n"); + } + + } + + return 0; +}