您的位置:首页 > 其它

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.

# 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: