题目
链接
http://poj.org/problem?id=2676
字面描述
Sudoku
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 34095 Accepted: 15284 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
Source
Southeastern Europe 2005
思路
定义三个数组判断i列是否出现j,i行是否出现j,第i个宫格是否出现j,依次枚举每一位的9种可能
根据上述三种数组来判断当前状态的合法性
代码实现
#include<cstdio>
#include<cstring>
#include<string.h>
using namespace std;
const int maxn=15;
int t;
int a[maxn][maxn];
bool flag;
bool x[maxn][maxn],y[maxn][maxn],k[maxn][maxn];//行,列,宫格
//判断第i行第j个数的所在宫格数记录
int m[maxn][maxn]={
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
{0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
{0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
{0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
{0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
{0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
{0, 7, 7, 7, 8, 8, 8, 9, 9, 9},
{0, 7, 7, 7, 8, 8, 8, 9, 9, 9},
{0, 7, 7, 7, 8, 8, 8, 9, 9, 9}
};
//遍历
inline void dfs(int x1,int y1){
//记录flag是为了只输出一个解
if(flag)return;
//输出
if(x1>9){
flag=1;
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++)printf("%d",a[i][j]);
printf("\n");
}
printf("\n");
return;
}
//有数本来就填出来了
if(a[x1][y1]){
if(y1==9)x1++,y1=1;
else y1++;
dfs(x1,y1);
return;
}
//枚举9中可能
for(int i=1;i<=9;i++){
//判断合法性
if(!x[x1][i]){
if(!y[y1][i]){
if(!k[m[x1][y1]][i]){
a[x1][y1]=i;
int x2=x1,y2=y1;
if(y2==9)x2++,y2=1;
else y2++;
x[x1][i]=true;
y[y1][i]=true;
k[m[x1][y1]][i]=true;
dfs(x2,y2);
x[x1][i]=false;
y[y1][i]=false;
k[m[x1][y1]][i]=false;
a[x1][y1]=0;
}
}
}
}
return;
}
int main(){
scanf("%d",&t);
while(t--){
flag=false;
memset(x,false,sizeof(x));
memset(y,false,sizeof(y));
memset(k,false,sizeof(k));
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
char op;
scanf(" %c",&op);
a[i][j]=op-'0';
if(!a[i][j])continue;
x[i][a[i][j]]=true;
y[j][a[i][j]]=true;
k[m[i][j]][a[i][j]]=true;
//printf("%d",a[i][j]);
}
}
dfs(1,1);
}
return 0;
}