题目:
你一定听说过“数独”游戏。
如【图1.png】,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
数独的答案都是唯一的,所以,多个解也称为无解。
本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。
本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。
格式要求,输入9行,每行9个数字,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。
例如:
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700
程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764
再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400
程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452
资源约定:
峰值内存消耗 < 256M
CPU消耗 < 2000ms
数独游戏,用dfs遍历,get新技能!!!!
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define maxn 105
using namespace std;
struct node
{
int x,y;
}p[100];
int mapp[11][11];
bool flag,row[11][11],col[11][11],gg[3][3][11];
void dfs(int step)
{
if(flag)
return ;
if(step==-1)
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cout << mapp[i][j];
}
cout << endl;
}
flag=true;
return ;
}
int x=p[step].x;
int y=p[step].y;
for(int i=1;i<=9;i++)
{
if(!row[x][i]&&!col[y][i]&&!gg[x/3][y/3][i])
{
row[x][i]=col[y][i]=gg[x/3][y/3][i]=true;
mapp[x][y]=i;
dfs(step-1);
row[x][i]=col[y][i]=gg[x/3][y/3][i]=false;
mapp[x][y]=0;
}
}
}
int main()
{
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(gg,false,sizeof(gg));
int cnt=0;
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
int t;
scanf("%1d",&t);
mapp[i][j]=t;
if(t)
{
row[i][t]=col[j][t]=gg[i/3][j/3][t]=true;
}
else
{
p[cnt].x=i;
p[cnt++].y=j;
}
}
}
flag=false;
dfs(cnt-1);
return 0;
}