POJ Sudoku 数独填数 DFS

时间:2024-12-15 23:07:37
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 18105   Accepted: 8772   Special Judge

Description

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 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 暑假艾教教的数独,留个板子。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int sudoku[][];
int column[][];
int row[][];
int nine[][];
struct node
{
int x,y;
};
node ready[];
int T;
int num = ;
char s[][];
int cal(int x,int y)
{
return (x-)/*+(y-)/+;
}
bool cmp(node A,node B)
{
return A.y>B.y;
}
void put(int x,int y,int tt,int flag)
{
if(flag) sudoku[x][y] = tt;
row[x][tt] = flag;
column[y][tt] = flag;
nine[cal(x,y)][tt] = flag;
}
int ok = ;
int can(int x,int y,int tt)
{
if(row[x][tt]) return ;
if(column[y][tt]) return ;
if(nine[cal(x,y)][tt]) return ;
return ;
}
void dfs(int k)
{
if(ok) return;
if(k==num+)
{
for(int i=;i<=;i++)
{
for(int j=;j<=;j++)
{
if(j==) printf("%d\n",sudoku[i][j]);
else printf("%d",sudoku[i][j]);
}
}
ok = ;
return;
}
for(int nex=;nex<=;nex++)
{
if(can(ready[k].x,ready[k].y,nex))
{
put(ready[k].x,ready[k].y,nex,);
dfs(k+);
put(ready[k].x,ready[k].y,nex,);
}
}
}
int main()
{
cin>>T;
while(T--)
{
ok = ;
memset(sudoku,,sizeof(sudoku));
memset(ready,,sizeof(ready));
memset(column,,sizeof(column));
memset(row,,sizeof(row));
memset(nine,,sizeof(nine));
num = ;
for(int i=;i<=;i++)
{
scanf("%s",s[i]+);
for(int j=;j<=;j++)
{
if(s[i][j]=='')
{
num++;
ready[num].x = i;
ready[num].y = j;
}
else
{
put(i,j,s[i][j]-'',);
}
}
}
sort(ready+,ready+num+,cmp);
dfs();
}
return ;
}