ADD file via upload

main
pacmjqzwe 3 weeks ago
parent 33b9bbf989
commit 83e1700f64

@ -0,0 +1,144 @@
#include<stdio.h>
#include<string.h>
int is_valid(int board[9][9], int row, int col, int num) {// 检查行;
for (int i = 0; i < 9; i++) {
if (board[row][i] == num) {
return 0;
}
}
for (int i = 0; i < 9; i++) {//检查列
if (board[i][col] == num) {
return 0;
}
}
int startr = row - row % 3;
int startc = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[startr + i][startc + j] == num) {
return 0;
}
}
}
return 1;
}//函数
int solve_sudoku(int board[9][9]) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (board[row][col] == 0) {
for (int num = 1; num <= 9; num++) {
if (is_valid(board, row, col, num)) {
board[row][col] = num;
if (solve_sudoku(board)) {
return 1;
}
board[row][col] = 0;
}
}
return 0;
}
}
}
return 1;
}
//函数
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}};
printf("The original Sudoku matrix:\n");
printf("|-----------------------|\n");
for(int i=0;i<9;i++){
printf("| ");
for(int j=0;j<9;j++){
printf("%d ",board[i][j]);
if((j+1)%3==0){
printf("| ");
}
}
printf("\n");
if((i+1)%3==0) {
printf("|-----------------------|\n");
}
//数组的输出;
}int a=0,b=0,c=0,d=1;
for(int i=0;i<9;i++){
for(int m=1;m<=9;m++){
for(int j=0;j<9;j++){
if(board[i][j]==m){
a=a+1;
if(a>1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the row %d has been used!\n",m,i+1);
return 0;
}
}
}a=0;
}
}
//行的判断
for(int start=0;start<=6;){
for(int end=0;end<=6;){
for(int m=1;m<9;m++){
for(int i=start;i<3;i++){
for(int j=end;j<3;j++){
if(board[i][j]==m){
c=c+1;}
if(c>1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the block %d has been used!\n",m,d);
return 0;
}
}
}
c=0;
}
end=end+3;
d=d+1;
}
start=start+3;
}
//方块的判断;
for(int i=0;i<9;i++){
for(int m=1;m<9;m++){
for(int j=0;j<9;j++){
if(board[j][i]==m){
b=b+1;}
if(b>1){
printf("False:Invalid initial Sudoku matrix!\n");
printf("The number %d in the col %d has been used!\n",m,i+1);
return 0;
}
}b=0;
}b=0;
}
printf("True:Valid initial Sudoku matrix!\n");
//这是对数组的判断,是否为数独数组
if (solve_sudoku(board)) {
printf("The solution of Sudoku matrix:\n");
printf("|-----------------------|\n");
for(int i=0;i<9;i++){
printf("| ");
for(int j=0;j<9;j++){
printf("%d ",board[i][j]);
if((j+1)%3==0){
printf("| ");
}
}
printf("\n");
if((i+1)%3==0) {
printf("|-----------------------|\n");
}
//数组的输出;
}
}else {
printf("No solution!\n");}
return 0;
}
Loading…
Cancel
Save