本一,刚刚起步算法如有不足,请指出。
其实看了好多博客吧,我感觉有些繁琐其实这个题思想很简单:其实关键在于处理小九宫格,
我把我都理解都有注释在代码中。(我不想多BB,简洁明了,上代码)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool vx[10][10];//行情况
bool vy[10][10];//列情况
bool vv[10][10];//九宫格
char sd[10][10];// 字符串
bool f=false;
void dfs(int x,int y)
{
if(f)
{
return ;
}
if(x==9)
{
f=true;
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
if(j<8)
printf("%c ",sd[i][j]);
else
printf("%c\n",sd[i][j]);
}
}
return ;
}
/*下面两个要注意顺序!!!!!*/
if(y==9)
{
dfs(x+1,0);
return ;
}
if(sd[x][y]!='*')
{
dfs(x,y+1);
return ;
}
/* */
for(int i=1; i<=9; i++)
{
if(!vv[x/3*3+y/3][i]&&!vx[x][i]&&!vy[y][i])
{
sd[x][y]='0'+i;
vv[x/3*3+y/3][i]=true;
vx[x][i]=true;
vy[y][i]=true;
dfs(x,y+1);
vv[x/3*3+y/3][i]=false;
vx[x][i]=false;
vy[y][i]=false;
sd[x][y]='*';
//避免后续不是*访问不到
}
}
}
int main()
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
// scanf("%c ",&sd[i][j]);
scanf(" %c",&sd[i][j]);
}
}
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
if(sd[i][j]!='*')
{
vx[i][sd[i][j]-'0']=true;
vy[j][sd[i][j]-'0']=true;
vv[i/3*3+j/3][sd[i][j]-'0']=true;
}//行 i[0,1,2,3,4,5,6,7,8]
// i/3 [0,1,2]*3=[0,3,6]
} // j/3 也是[0,1,2] 相加和的范围如下
// 0+0=0 0+1=1 0+2=2
// 3+0=3 3+1=4 3+2=5
// 6+0=6 6+1=7 6+2=8
// 这也就是对应了九个小九宫格
}
dfs(0,0);
return 0;
}
重点就是主函数里面的注释,我相信很多人和我一样因此绊住了脚。
希望我们的每一天都有进步,加油!
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuo8.com 版权所有 湘ICP备2023022238号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务