POJ - 2676 Sudoku 数独游戏 dfs神奇的反搜

时间:2022-02-20 14:32:47

Sudoku

Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task. 
POJ - 2676 Sudoku 数独游戏 dfs神奇的反搜

Input

The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.

Output

For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

Sample Input

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

Sample Output

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127 数独游戏。感觉这道题的代码还是蛮实用的~思路是dfs从头到尾依次枚举每个0点,尝试填入1->9,不合适再返回上层,直到填满0为止。
还有就是反搜(0ms),虽然我不会证明,但是和正搜(891ms)对比,是不是很神奇?
#include<stdio.h>
#include<string.h> char aa[][];
int a[][];
int row[][],col[][],squ[][];
int c1,c2,f; int jud(int x,int y)
{
if(x<=&&y<=) return ;
if(x<=&&<=y&&y<=) return ;
if(x<=&&<=y) return ;
if(<=x&&x<=&&y<=) return ;
if(<=x&&x<=&&<=y&&y<=) return ;
if(<=x&&x<=&&<=y) return ;
if(<=x&&y<=) return ;
if(<=x&&<=y&&y<=) return ;
if(<=x&&<=y) return ;
} void dfs()
{
int i,j,k;
if(f==) return;
if(c1==c2){
f=;
for(i=;i<=;i++){
for(j=;j<=;j++){ //反搜枚举9->1
printf("%d",a[i][j]);
}
printf("\n");
}
return;
}
for(i=;i<=;i++){
for(j=;j<=;j++){
if(a[i][j]==){
for(k=;k<=;k++){
if(row[i][k]==&&col[j][k]==&&squ[jud(i,j)][k]==){
row[i][k]=;
col[j][k]=;
squ[jud(i,j)][k]=;
a[i][j]=k;
c2++;
dfs();
row[i][k]=;
col[j][k]=;
squ[jud(i,j)][k]=;
a[i][j]=;
c2--;
}
}
return;
}
}
}
} int main()
{
int t,i,j;
scanf("%d",&t);
while(t--){
memset(a,,sizeof(a));
memset(row,,sizeof(row));
memset(col,,sizeof(col));
memset(squ,,sizeof(squ));
c1=;
for(i=;i<;i++){
getchar();
scanf("%s",aa[i]);
for(j=;j<;j++){
a[i+][j+]=aa[i][j]-'';
if(a[i+][j+]==) c1++;
else{
row[i+][a[i+][j+]]=;
col[j+][a[i+][j+]]=;
squ[jud(i+,j+)][a[i+][j+]]=;
}
}
}
c2=;f=;
dfs();
}
return ;
}