C/C++编程小练习 数独(DFS算法实现)
2016-11-24 21:42
330 查看
数独(DFS算法实现)
代码:
运行结果会生成多个解(去掉goto)
代码:
#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)
相关文章推荐
- 【算法】POJ2676,HDU4069解决数独的两种实现:DFS、DLX
- 关于"数独--九宫格"的算法实现
- 无向图的DFS和BFS算法实现
- 解数独算法--C++实现
- java实现数独的算法
- 图结构练习——判断给定图是否存在合法拓扑序列(dfs算法(第一个代码),邻接矩阵(前两个代码),邻接表(第三个代码))
- 练习:利用颜色直方图匹配算法实现图像中目标的识别
- Javascript 实现的数独解题算法网页实例
- 二分图匹配匈牙利算法DFS实现
- Clojure:算法练习的实现(二)——合并排序
- 算法练习:砍树,不相邻(JAVA实现)
- 有向图的DFS和BFS算法实现
- DFS深度搜索算法实现深度探究解析-以POJ 1040为例
- 算法练习之二叉查找树 C++实现
- 构造数独 算法及代码实现
- 数独问题的一种简单算法代码实现
- 算法练习五 红黑树上 实现了左旋转、右旋转、以及插入
- 二分图匹配(匈牙利算法DFS实现)
- 解数独算法--C++实现
- Javascript 实现的数独解题算法网页实例