[YBT high-efficiency advanced] 1 basic algorithm/4 depth-first search/2 Sudoku game
Memory limit: 256 MiB
Time limit: 1000 ms
standard input and output
Question type: Traditional
Evaluation method: Text comparison
Title description
Sudoku is a traditional puzzle game, you need to put 9 ∗ 9 9*99∗The Sudoku of 9 is complete, so that each row, each column, each3 ∗ 3 3*33∗The number1 − 9 1-9 in the ninesquare grid of 31−9 all appear exactly once.
Please write a program to fill in Sudoku.
Input format
The input contains multiple sets of test cases.
Each test case occupies a line, contains 81 characters, and expresses the data in the 81 cells of Sudoku (the overall order is from top to bottom, and the same line from left to right).
Each character is a number or a ".". (Indicating that it has not been filled).
You can assume that each puzzle in the input has only one solution.
A single line containing the word end at the end of the file indicates the end of input.
Output format
For each test case, one line of data is output, representing the filled Sudoku.
Sample
Sample input
4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......
......52..8.4......3...9...5.1...6..2..7........3.....6...1..........7.4.......3.
end
Sample output
417369825632158947958724316825437169791586432346912758289643571573291684164875293
416837529982465371735129468571298643293746185864351297647913852359682714128574936
Ideas
Use 3 arrays to save the digital usage of each row and column.
Depth-first search
Find the answer, mark, and exit
Code
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
string str;
int h[9],l[9],g[9],x[82],y[82],z[82],w[82],num[513],s[513],tot,m[10]={
1,2,4,8,16,32,64,128,256,512};
bool d;
void DFS(int dep)
{
int bit,tem,mn=100000000,wz,i;
if(dep>tot)
{
cout<<str<<endl;
d=1;
return;
}
for(i=1; i<=tot; i++)
if(str[w[i]]=='.'&&s[h[x[i]]&l[y[i]]&g[z[i]]]<=mn)
{
wz=i,mn=s[h[x[i]]&l[y[i]]&g[z[i]]];
if(mn==0)return;
}
for(bit=h[x[wz]]&l[y[wz]]&g[z[wz]]; bit; bit-=tem)
{
tem=bit&-bit,h[x[wz]]^=tem,l[y[wz]]^=tem,g[z[wz]]^=tem,str[w[wz]]=num[tem]+'0';
DFS(dep+1);
if(d)return;
h[x[wz]]^=tem,l[y[wz]]^=tem,g[z[wz]]^=tem;
}
str[w[wz]]='.';
return;
}
int main()
{
int i,tem;
ios::sync_with_stdio(false);
memset(s,0,sizeof(s));
for(i=0; i<9; i++)num[m[i]]=i+1;
for(i=0; i<512; i++)
for (tem=i; tem; tem-=tem&-tem,s[i]++);
for(cin>>str; str!="end"; cin>>str)
{
for(i=0; i<9; i++)
h[i]=l[i]=g[i]=511;
for(tot=0,d=0,i=0; i<81; i++)
if(str[i]=='.') w[++tot]=i,x[tot]=i/9,y[tot]=i%9,z[tot]=x[tot]/3*3+y[tot]/3;
else h[i/9]^=m[str[i]-49],l[i%9]^=m[str[i]-49],g[i/27*3+(i%9)/3]^=m[str[i]-49];
DFS(1);
}
return 0;
}