您的位置:首页 > 编程语言 > C语言/C++

C/C++编程小练习 数独(DFS算法实现)

2016-11-24 21:42 330 查看
数独(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]
==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]
==1&&test[x]
==i){
flag=false;
goto X;
}
}
}

if(flag==true){
mark[m]
=1;
test[m]
=i;
dfs(m,n+1);
mark[m]
=0;
}
X: //这里输出一个解后就跳出了,把goto去掉会生成所有解
flag=true;
}
}
}


运行结果会生成多个解(去掉goto)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: