Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 14480 | Accepted: 7153 | 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.

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
数独;
标记num这个数在第i行,第j列,第k个矩阵中有没有出现,不停地往下Dfs失败了就回溯;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int Map[10][10];
int row[10][10];//标记9行
int col[10][10];//标记9列
int grid[10][10];//标记9个9宫格
int getgrid(int x,int y){
return 3*( x/3 )+(y/3);
}
int Dfs(int x,int y){
if(x==10)
return 1;
int flag=0;
if(Map[x][y]){
if(y==9)
flag=Dfs(x+1,1);
else
flag=Dfs(x,y+1);
if(flag)
return 1;
else
return 0;
}
int k=getgrid(x-1,y-1);
for(int i=1;i<=9;i++){
if(!Map[x][y]&&!col[y][i]&&!row[x][i]&&!grid[k][i]){
Map[x][y]=i;
col[y][i]=1;
row[x][i]=1;
grid[k][i]=1;
if(y==9)
flag=Dfs(x+1,1);
else
flag=Dfs(x,y+1);
if(!flag){
Map[x][y]=0;
col[y][i]=0;
row[x][i]=0;
grid[k][i]=0;
}
else
return 1;
}
}
return 0;
}
int main(){
int T;
char str[10];
scanf("%d",&T);
while(T--){
memset(Map,0,sizeof(Map));
memset(row,0,sizeof(row));
memset(col,0,sizeof(col));
memset(grid,0,sizeof(grid));
for(int i=1;i<=9;i++){
scanf("%*c%s",str);
for(int j=0;j<9;j++){
Map[i][j+1]=str[j]-'0';
int x=Map[i][j+1];
if(x){
row[i][x]=1;
col[j+1][x]=1;
int k=getgrid(i-1,j);
grid[k][x]=1;
}
}
}
Dfs(1,1);
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
cout<<Map[i][j];
}
cout<<endl;
}
}
return 0;
}