题目意思:hdu1426,?的位置填数字,每行每列及所在3*3区域数字不能重复。
解题思路:显而易见,用数组记录每个点的访问情况,遍历矩阵,每个点八个方向bfs,用count记录deposit的个数。
代码明细:
//probID: hdu1426
//author: WiselyQY
//date: 2020-12-28
#include <bits/stdc++.h>
using namespace std;
//flag用于标记是否为第一个case
int g[9][9],ok,flag;
//用于返回在第几区域,该区域内数字不能重复
void region(const int x, const int y, int& sx, int& sy, int& ex, int& ey)
{
if(x>=0 && x<=2)
{
if(y>=0 && y<=2) {sx=0; sy=0; ex=2; ey=2;}
if(y>=3 && y<=5) {sx=0; sy=3; ex=2; ey=5;}
if(y>=6 && y<=8) {sx=0; sy=6; ex=2; ey=8;}
}
if(x>=3 && x<=5)
{
if(y>=0 && y<=2) {sx=3; sy=0; ex=5; ey=2;}
if(y>=3 && y<=5) {sx=3; sy=3; ex=5; ey=5;}
if(y>=6 && y<=8) {sx=3; sy=6; ex=5; ey=8;}
}
if(x>=6 && x<=8)
{
if(y>=0 && y<=2) {sx=6; sy=0; ex=8; ey=2;}
if(y>=3 && y<=5) {sx=6; sy=3; ex=8; ey=5;}
if(y>=6 && y<=8) {sx=6; sy=6; ex=8; ey=8;}
}
}
//同一行或同一列,或同一区域内不能重复
int check(int x, int y, int num)
{
for(int i=0; i<9; i++)
if(g[i][y]==num) return 0;
for(int i=0; i<9; i++)
if(g[x][i]==num) return 0;
int sx,sy,ex,ey;
region(x,y,sx,sy,ex,ey);
for(int i=sx; i<=ex; i++)
for(int j=sy; j<=ey; j++)
if(g[i][j]==num) return 0;
return 1;
}
//dfs,得到结果直接输出
void dfs(int x, int y)
{
if(ok) return;
while(x<9 && g[x][y])
{
y++;
if(y==9) {x++; y=0;}
}
if(x==9)
{
if(flag) flag=0;
else cout<<endl;
ok=1;
for(int i=0; i<9;i++)
{
cout<<g[i][0];
for(int j=1; j<9; j++)
cout<<" "<<g[i][j];
cout<<endl;
}
return;
}
int gn[9][9];
memcpy(gn,g,sizeof(g));
for(int i=1; i<=9; i++)
{
if(!g[x][y] && check(x,y,i))
{
g[x][y]=i;
int nx=x, ny=y;
ny++;
if(ny==9){nx++;ny=0;}
dfs(nx,ny);
}
memcpy(g,gn,sizeof(gn));
}
}
int main()
{
clock_t start,end;
start=clock();
#ifndef ONLINE_JUDGE
freopen(R"(D:\hdu\1426\in.txt)","r",stdin);
#endif
flag=1;
char ch[9][9];
while(cin>>ch[0][0])
{
for(int i=1; i<9;i++) cin>>ch[0][i];
for(int i=1; i<9;i++)
for(int j=0; j<9; j++) cin>>ch[i][j];
//?的全部标记为0
for(int i=0; i<9;i++)
for(int j=0; j<9; j++)
{
if(ch[i][j]=='?') g[i][j]=0;
else g[i][j]=ch[i][j]-'0';
}
ok=0;
dfs(0,0);
}
end=clock();
//printf("time=%lfs\n",(double)(end-start)/1000);
return 0;
}