Sudoku--POJ 2676

1、解题思路:经典深度搜索。

2、注意事项:输入单个字符scanf、cin.get();DFS中搜索比较位置的判断;正搜超时,反搜0ms。

3、实现方法

#include<iostream>
using namespace std;

struct Node
{
int num;
bool change;
};

struct Pos
{
int x,y;
};

int begin[4]={0,1,4,7};
int end[4]={0,3,6,9};

Node map[
10][10];
Pos Arr[
100];
int cnt,mark;

void Init()
{
char ch;
mark
=0;
cnt
=0;
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
scanf(
"%c",&ch);
map[i][j].num
=int(ch-'0');
if(map[i][j].num==0)
{
map[i][j].change
=true;
cnt
++;
Arr[cnt].x
=i;
Arr[cnt].y
=j;
}
else
map[i][j].change
=false;
}
cin.
get(ch);
}
}

bool Judge(int step,int num)
{
int x=Arr[step].x;
int y=Arr[step].y;
for(int i=1;i<=9;i++)
{
if(i==y||map[x][i].num!=num)
continue;
else
return false;
}
for(int j=1;j<=9;j++)
{
if(j==x||map[j][y].num!=num)
continue;
else
return false;
}
int tmp_x=x/3;
if(x%3!=0)
tmp_x
++;
int tmp_y=y/3;
if(y%3!=0)
tmp_y
++;
for(int p=begin[tmp_x];p<=end[tmp_x];p++)
{
for(int q=begin[tmp_y];q<=end[tmp_y];q++)
{
if((p==x&&q==y)||map[p][q].num!=num)
continue;
else
return false;
}
}
return true;
}

void DFS(int step)
{
if(step==1)
{
mark
=1;
for(int j=1;j<=9;j++)
{
if(Judge(step,j))
{
map[Arr[step].x][Arr[step].y].num
=j;
DFS(step
-1);
if(!mark)
map[Arr[step].x][Arr[step].y].num
=0;
}
}
}
if(!mark)
{
for(int i=1;i<=9;i++)
{
if(Judge(step,i))
{
map[Arr[step].x][Arr[step].y].num
=i;
DFS(step
-1);
if(!mark)
map[Arr[step].x][Arr[step].y].num
=0;
}
}
}
}

int main()
{
int n;
char s;
cin
>>n;
cin.
get(s);
while(n--)
{
Init();
DFS(cnt);
if(mark)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
cout
<<map[i][j].num;
cout
<<endl;
}
}
}
return 0;
}

 

posted @ 2010-07-23 21:13  勇泽  阅读(1389)  评论(2编辑  收藏  举报