题目描述
数独是根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个粗线宫内的数字均含1-9,不重复。每一道合格的数独谜题都有且仅有唯一答案,推理方法也以此为基础,任何无解或多解的题目都是不合格的。
芬兰一位数学家号称设计出全球最难的“数独游戏”,并刊登在报纸上,让大家去挑战。
这位数学家说,他相信只有“智慧最顶尖”的人才有可能破解这个“数独之谜”。
据介绍,目前数独游戏的难度的等级有一到五级,一是入门等级,五则比较难。不过这位数学家说,他所设计的数独游戏难度等级是十一,可以说是所以数独游戏中,难度最高的等级他还表示,他目前还没遇到解不出来的数独游戏,因此他认为“最具挑战性”的数独游戏并没有出现。
输入格式
一个未填的数独
输出格式
填好的数独
思路
dfs,深度优先搜索。
先上代码
#include<iostream>
#include<ctime>
#include<stdlib.h>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<cstdio>
using namespace std;
int map[10][10];
int a=0;
typedef struct A
{
int x;
int y;
}A;
A qc[90];
bool hang[10][10]={0};
bool lie[10][10]={0};
bool gong[3][3][10]={0};
void shuchu()
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
cout<<map[i][j]<<' ';
}
cout<<"\n";
}
}
void dfs(int now){
int x=qc[now].x;
int y=qc[now].y;
if(now==a)
{
shuchu();
}
else
{
for(int i=1;i<=9;i++)
{
//判断i是否符合要求
//每一行、每一列、每一个粗线宫内的数字均含1-9,不重复
if(!hang[x][i]&&!lie[y][i]&&!gong[(x-1)/3][(y-1)/3][i]){
// 修改(x,y) i
map[x][y]=i;
hang[x][i]=true;
lie[y][i]=true;
gong[(x-1)/3][(y-1)/3][i]=true;
dfs((now+1));
hang[x][i]=false;
lie[y][i]=false;
gong[(x-1)/3][(y-1)/3][i]=false;
//回溯
}
}
}
}
int main()
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
cin>>map[i][j];
if(map[i][j]==0)
{
qc[a].x=i;
qc[a].y=j;
a++;
}
else
{
hang[i][map[i][j]]=true;
lie[j][map[i][j]]=true;
gong[(i-1)/3][(j-1)/3][map[i][j]]=true;
}
}
}
dfs(0);
return 0;
}
注意点
1.寻找空缺
通过qc结构体数组,加快速度。
if(map[i][j]==0)
{
qc[a].x=i;
qc[a].y=j;
a++;
}
直接使用。
int x=qc[now].x;
int y=qc[now].y;
2.去重
if(!hang[x][i]&&!lie[y][i]&&!gong[(x-1)/3][(y-1)/3][i])
3.状态回溯
在使用后注意数组的状态回溯,方便下次使用。
hang[x][i]=false;
lie[y][i]=false;
gong[(x-1)/3][(y-1)/3][i]=false;