数度问题。 这道题就是做好行和列以及方块的标记就好,不用考虑优化。。。
#include<stdio.h>
#include<string.h>
int judgeh[10][10],judgel[10][10],judgef[10][10];
char map[10][10];
int sum;
int yes;
void dfs(int x,int y){
int nx,ny,i;
if(yes==1){
return;
}
if(map[x][y]=='0'){
int f=((x/3))*3+(y/3)+1;
for(i=1;i<=9;i++){
if(judgeh[x][i]==0&&judgel[y][i]==0&&judgef[f][i]==0){
ny=y+1;
nx=x;
map[x][y]='0'+i;
judgeh[x][i]=1;
judgel[y][i]=1;
judgef[f][i]=1;
if(ny==9){
ny=0;
nx++;
}
if(nx==9){
yes=1;
return;
}
dfs(nx,ny);
if(yes==1) return;
map[x][y]='0';
judgeh[x][i]=0;
judgel[y][i]=0;
judgef[f][i]=0;
}
}
}
else{
nx=x;
ny=y+1;
if(ny>=9){
ny=0;
nx++;
}
if(nx>=9){
yes=1;
return;
}
dfs(nx,ny);
}
return;
}
int main(){
int t;
scanf("%d\n",&t);
while(t--){
memset(judgeh,0,sizeof(judgeh));
memset(judgel,0,sizeof(judgel));
memset(judgef,0,sizeof(judgef));
for(int i=0;i<9;i++) scanf("%s",map[i]);
sum=0;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(map[i][j]!='0'){
int date=map[i][j]-'0';
judgeh[i][date]=1;
judgel[j][date]=1;
int f=((i/3))*3+(j/3)+1;
judgef[f][date]=1;
}
else {
sum++;
}
}
}
yes=0;
dfs(0,0);
for(int i=0;i<9;i++) printf("%s\n",map[i]);
}
return 0;
}