数独(DFS算法实现)
代码:
#include <cstdio>
#include <cstdlib>
int test[9][9]={
0,0,5,3,0,0,0,0,0,
8,0,0,0,0,1,0,2,0,
0,7,0,0,1,0,5,0,0,
4,0,0,0,0,5,3,0,0,
0,1,0,0,7,0,0,0,6,
0,0,3,2,9,0,0,8,0,
0,6,0,5,0,0,0,0,9,
0,0,0,0,0,0,0,3,0,
0,0,0,0,0,9,7,0,0
};
int mark[9][9];
bool flag=true;
bool ok=false;
int cnt;
void dfs(int m,int n);
int main()
{
for(int i=0;i<9;++i){
for(int j=0;j<9;++j){
if(test[i][j]!=0){
mark[i][j]=1;
}
}
}
dfs(0,0);
return 0;
}
void dfs(int m,int n)
{
if(ok==true){
return;
}
if(m==8&&n==9){//边界
printf("%d:\n",++cnt);
for(int i=0;i<9;++i){
for(int j=0;j<9;++j){
printf("%d ",test[i][j]);
}
printf("\n");
}
printf("\n");
ok=true;
return;
}else{
if(n==9){//一行到了边界
dfs(m+1,0);
return ;
}
if(mark[m][n]==1){//若填过了
dfs(m,n+1);//跳到下一格
return;
}
for(int i=1;i<=9;++i){
for(int x=0;x<9;++x){
for(int y=0;y<9;++y){
if(mark[m][y]==1&&test[m][y]==i||
mark[x][n]==1&&test[x][n]==i){
flag=false;
goto X;
}
}
}
if(flag==true){
mark[m][n]=1;
test[m][n]=i;
dfs(m,n+1);
mark[m][n]=0;
}
X: //这里输出一个解后就跳出了,把goto去掉会生成所有解
flag=true;
}
}
}
运行结果会生成多个解(去掉goto)