[Ybtoj High-Efficiency Advanced 1.4] [Deep Search] Sudoku Game
topic
Problem-solving ideas
Use string input to
convert it into a numeric value and put it into the array a.
Array l to count the usage of the current row number.
Array r to count the usage of the current column number.
Array f to count the usage of the current 3*3 square number.
Enumeration can fill in the current grid. The number
Code
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int a[10][10],l[10][10],r[10][10],f[5][5][10],p;
string s;
int k(int x)
{
if (x<4) return 1;
if (x<7) return 2;
return 3;
}
void dfs(int x,int y)
{
if (p) return; //已经输出答案
if (x>9) //
{
for (int i=1;i<=9;i++)
for (int j=1;j<=9;j++)
printf("%d",a[i][j]);
printf("\n");
p=1;
return;
}
if (a[x][y])
if (y==9)
dfs(x+1,1);
else dfs(x,y+1);
for (int i=1;i<=9;i++)
if (!l[x][i]&&!r[y][i]&&!f[k(x)][k(y)][i]&&a[x][y]==0) //判断是否能填
{
a[x][y]=i;
l[x][i]=r[y][i]=f[k(x)][k(y)][i]=1;
if (y==9)
dfs(x+1,1);
else dfs(x,y+1);
l[x][i]=r[y][i]=f[k(x)][k(y)][i]=0;
a[x][y]=0; //回溯
}
}
int main()
{
while (cin>>s)
{
if(s=="end")
return 0;
p=0;
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
memset(f,0,sizeof(f)); //清0
for (int i=1;i<=9;i++)
for (int j=1;j<=9;j++)
if (s[(i-1)*9+j-1]!='.')
{
a[i][j]=s[(i-1)*9+j-1]-48;
l[i][a[i][j]]=1;
r[j][a[i][j]]=1;
f[k(i)][k(j)][a[i][j]]=1;
}
else a[i][j]=0; //预处理
dfs(1,1);
}
return 0;
}