POJ-2676 Sudoku (DFS)
2015-08-13 09:14
405 查看
Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.
View Code
# include<iostream> # include<cstdio> # include<cstring> # include<algorithm> using namespace std; char p[12][12]; int cnt,a[12][12]; struct Position { int x,y; Position(){} Position(int a,int b):x(a),y(b){} bool operator < (const Position &a) const { if(x==a.x) return y<a.y; return x<a.x; } }; bool yy; Position pos[100]; bool ok(int x,int y,int m) { for(int k=1;k<=9;++k){ if(a[x][k]==m||a[k][y]==m) return false; } int it=x,jt=y; while(it%3!=1) --it; while(jt%3!=1) --jt; for(int i=it;i<=it+2;++i) for(int j=jt;j<=jt+2;++j) if(a[i][j]==m) return false; return true; } void dfs(int p) { if(yy) return ; if(p==cnt){ for(int i=1;i<=9;++i){ for(int j=1;j<=9;++j) printf("%d",a[i][j]); printf("\n"); } yy=true; return ; } int x=pos[p].x,y=pos[p].y; for(int i=1;i<=9;++i){ if(ok(x,y,i)){ a[x][y]=i; dfs(p+1); a[x][y]=0; ///注意要将这个位置重新置为0,否则影响接下来的搜索过程。 } if(yy) return ; } } int main() { int T; scanf("%d",&T); while(T--) { cnt=0; for(int i=1;i<=9;++i){ scanf("%s",p[i]+1); for(int j=1;j<=9;++j){ a[i][j]=p[i][j]-'0'; if(a[i][j]==0){ pos[cnt++]=Position(i,j); } } } sort(pos,pos+cnt); yy=false; dfs(0); } return 0; }
View Code
相关文章推荐
- [转]Java中fina以及static的意义
- PHP的数据类型转换
- ORDER BY子句
- POJ 1789:Truck History 【Prim】
- 程序员不要怀疑自己,你们本来就很优秀
- 赛门铁克、VERITAS中国区高管首谈分拆后公司发展
- 架构师速成8.4-分库分表的关键点
- Time Changes Everything
- 普林斯顿大学公开课 算法1-8:并检查集合 高速查找
- Objective-C:继承、分类(Category、extension)、协议(protocol),个人理解,仅供参考
- [CodeForces 300C Beautiful Numbers]组合计数
- 如何在WIN7中关闭JAVA自动更新
- 深入理解计算机操作系统——第7章:静态链接
- C#-遍历datatable的几种方法
- onSaveInstanceState和onRestoreInstanceState触发的时机
- win10 qq登陆不了怎么办?Win10qq提示无法访问个人文件夹的解决办法
- Spring 学习笔记(一)
- hive cli启动报错
- javascript获取本机操作系统类型的方法
- javase的多线程断点下载