Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.
Input
The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.
Output
For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.
Sample Input
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107
Sample Output
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
具体代码过程如下:参考链接https://www.cnblogs.com/PJQOOO/p/4074644.html
#include<iostream>
#include<cstring>
using namespace std;
//考虑为bool类型也可以实现
int row[10][10];//判断row[i][x],在i行x是否出现(bool)
int col[10][10];//判断 col[j][y],在j列y是否出现(bool)
int map[10][10];//处理输入
int small[10][10];//处理3*3格子(bool)
int f(int x,int y){
return 3*((x-1)/3)+(y-1)/3+1;//返回x,y出现在哪个具体的网格
}
void init(){
int i,j;
char ch;
memset(row,0,sizeof(row));
memset(col,0,sizeof(col));
memset(small,0,sizeof(small));
for(i=1;i<=9;i++){
for(j=1;j<=9;j++){
scanf("%c",&ch);
map[i][j]=ch-'0';
if(map[i][j]){//不处理0的情况
int k;
k=f(i,j);
row[i][map[i][j]]=1;//在i行出现map[i][j];
col[j][map[i][j]]=1;//在j列出现map[i][j];
small[k][map[i][j]]=1;//map[i][j]属于第k个网格
}
}
getchar();
}
}
int dfs(int x,int y){
if(x==10)
return 1;
int flag=0;
if(map[x][y]){
if(y==9)
flag=dfs(x+1,1);
else
flag=dfs(x,y+1);
if(flag)
return 1;
else
return 0;
}
else{
int k=f(x,y);
for(int i=1;i<=9;i++)
if(!row[x][i]&&!col[y][i]&&!small[k][i]){
map[x][y]=i;
row[x][i]=1;
col[y][i]=1;
small[k][i]=1;
if(y==9)
flag=dfs(x+1,1);
else
flag=dfs(x,y+1);
if(!flag){
map[x][y]=0;
row[x][i]=0;
col[y][i]=0;
small[k][i]=0;
}
else
return 1;
}
}
return 0;
}
int main(){
int t;
scanf("%d",&t);
getchar();
while(t--){
init();//处理输入问题
dfs(1,1);//从当前的位置开始搜索dfs();
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++)
printf("%d",map[i][j]);
printf("\n");
}
}
}