题目:
https://www.luogu.org/problem/show?pid=1784
爆搜;
dfs中flag的应用;
42行 无解时赋为0,如果有解赋为0,那本来赋值的会变为0;
注意:
这个题有点特殊;
有的数(初始的)不能修改;
这不是剪枝……有回溯……;
总结:
基础不扎实;
注意什么时候应该用flag
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int ma[12][12],a[121];
bool vis[12][12],flag=1,hh[12][12];
bool pd(int x,int y,int now)
{
int fx,fy;
for(int i=1;i<=9;i++)
if(ma[i][y]==now || ma[x][i]==now) return false;
if(x<=3) fx=1;
else if(x>3 && x<=6) fx=4;
else fx=7;
if(y<=3) fy=1;
else if(y>3 && y<=6) fy=4;
else fy=7;
for(int i=fx;i<=fx+2 && i<=9;i++)
for(int j=fy;j<=fy+2 && j<=9;j++)
if(ma[i][j]==now) return false;
return true;
}
void dfs(int x)
{
int fx,fy;
if(x==82) {flag=0;return;}
if(x%9==0) fx=x/9;
else fx=x/9+1;
fy=x-(fx-1)*9;
if(ma[fx][fy]) dfs(x+1);
else if(flag)
{
for(int j=1;j<=9;j++)
{
if(pd(fx,fy,j))
{
ma[fx][fy]=j;
dfs(x+1);
}
}
if(flag) ma[fx][fy]=0;
}
return;
}
void solve()
{
for(int i=1;i<=9;i++)
for(int j=1;j<=9;j++)
scanf("%d",&ma[i][j]);
dfs(1);
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++) cout<<ma[i][j]<<" ";
cout<<endl;
}
return;
}
int main()
{
solve();
return 0;
}
本文详细介绍了洛谷第1784题的数独解决方案,主要使用了深度优先搜索(DFS)策略。在DFS过程中,讨论了如何利用flag进行有效操作,尤其是在遇到无解或已有解的情况时如何处理。需要注意的是,该题的部分数字是不能修改的,并且这里采用的不是剪枝技巧,而是带有回溯的搜索方法。最后,作者反思自己的基础知识不够牢固,强调在何时使用flag标志位的重要性。
1783

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



