数独(回溯)
2016-03-18 15:48
387 查看
#include <iostream> using namespace std; void search(int step); bool mark(int step); int ans=0; int a[9][9]; int main() { int i,j; for (i=0;i<9;i++) for (j=0;j<9;j++) cin>>a[i][j]; search(0); return 0; } void search(int step) { int i,j; int row=step/9;//行 int col=step%9;//列 if (step==81) { for (i=0;i<9;i++) { for (j=0;j<9;j++) cout<<a[i][j]; cout<<endl; } } else if (a[row][col]==0) { for (i=1;i<=9;i++) { a[row][col]=i; if (mark(step)) search(step+1); } a[row][col]=0;//回溯 } else search(step+1); } bool mark(int step)//判断数字 { int i,j; int row=step/9; int col=step%9; //判断行 for (i=0;i<9;i++) if (a[row][col]==a[row][i] && col!=i) return false; //判断列 for (i=0;i<9;i++) if (a[row][col]==a[i][col] && row!=i) return false; //判断宫 int tempRow=row/3*3;//每个宫的行 int tempCol=col/3*3;//每个宫的列 for (i=tempRow;i<tempRow+3;i++) for (j=tempCol;j<tempCol+3;j++) if (a[row][col]==a[i][j] && row!=i && col!=j) return false; //如果都符合,则返回真 return true; }
相关文章推荐
- SQL Server判断对象是否存在
- MySQL 数据库设计初步规范
- Mac 安装zookeeper
- cas单点登录登出配置,学习记录
- 活动的生命周期(Activity Lifecycle)
- jQuery.Autocomplete实现自动完成功能(详解)
- CPropertySheet使用示例
- jQuery事件与应用
- Java中字符串的不变性
- Activity的四种启动模式
- 提高工作效率
- dos和groovy和linq的关联
- plsql和jetty和word的关联
- 基类析构函数为virtual的好处
- 邻接表/邻接矩阵
- samba和ruby和sybase的关联
- JSTL FOREACH标签的varStatus状态属性
- tomcat和tomcat和mangodb的关联
- linq和ssh和windows的关联
- maven实战常见错误与解决方法