#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<queue>
#include<stack>
#include<bitset>
#include<iomanip>
#include<algorithm>
#include<string>
#include<cstring>
#define inf 100000
using namespace std;
int t[15][15];
bool area[15][15],hang[15][15],lie[15][15];
int x,cnt;
void dfs(){
int cnt=inf,x,y;
for (int i=1;i<=9;i++)
for (int j=1;j<=9;j++)
if(t[i][j]==0)
{
int cntt=0;
for (int k=1;k<=9;k++)
if (!hang[i][k]&&!lie[j][k]&&!area[((i+2)/3-1)*3+(j+2)/3][k])
cntt++;
if (cnt>cntt)
{
x=i;
y=j;
cnt=cntt;
}
}
if (cnt==inf)
{
for (int i=1;i<=9;i++)
{
for (int j=1;j<=9;j++)
{
printf ("%d ",t[i][j]);
}
printf ("\n");
}
exit(0);//here
}
for (int k=1;k<=9;k++)
if (!hang[x][k]&&!lie[y][k]&&!area[((x+2)/3-1)*3+(y+2)/3][k])
{
hang[x][k]=true;
lie[y][k]=true;
area[((x+2)/3-1)*3+(y+2)/3][k]=true;
t[x][y]=k;
dfs();
hang[x][k]=false;
lie[y][k]=false;
area[((x+2)/3-1)*3+(y+2)/3][k]=false;
t[x][y]=0;
}
}
int main (){
freopen ("sudoku.in","r",stdin);
//freopen ("sudoku.out","w",stdout);
for (int i=1;i<=9;i++)
for (int j=1;j<=9;j++)
{
scanf ("%d",&t[i][j]);
hang[i][t[i][j]]=true;
lie[j][t[i][j]]=true;
area[((i+2)/3-1)*3+(j+2)/3][t[i][j]]=true;
}
dfs();
return 0;
}洛谷 P1784 数独
最新推荐文章于 2024-12-10 21:58:08 发布
本文介绍了一种使用深度优先搜索解决数独问题的C++实现方法。通过预处理已知数字并利用递归函数进行回溯查找所有可能的解,最终输出完整的数独解答。
508

被折叠的 条评论
为什么被折叠?



