您的位置:首页 > 其它

POJ 2676 Sudoku

2015-07-28 19:56 429 查看
F - Sudoku
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice POJ
2676

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


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[20][20],b[20][20],c[5][5][20],m[20][20],h;//a,b,c数组分别用来判断行、列、九宫数字互异性
int ex(int x){
if (x%3==0) return x/3;
else return x/3+1;
}

void dfs(int x,int y){//以坐标为参数搜索
int i,j,nx=x,ny=y;
if (h) return;
if (x>9){
h=1;
for (i=1;i<=9;i++){
for (j=1;j<=9;j++) cout<<m[i][j];
cout<<endl;
}
} else {
ny++;if (ny>9) {ny=1;nx++;}
if (m[x][y]!=0) dfs(nx,ny);
else {
int xx=ex(x),yy=ex(y);
for (i=1;i<=9;i++){
if (!a[x][i] && !b[y][i] && !c[xx][yy][i]){
m[x][y]=i;
a[x][i]++;b[y][i]++;c[xx][yy][i]++;
dfs(nx,ny);
a[x][i]--;b[y][i]--;c[xx][yy][i]--;
m[x][y]=0;
if (h) return;
}
}
}

}
}

int main()
{
char ch;
int t;
cin>>t;
while (t--){
int i,j,x,y;
h=0;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
for (i=1;i<=9;i++){
for (j=1;j<=9;j++) {
cin>>ch;
m[i][j]=ch-'0';
x=ex(i);y=ex(j);
a[i][ch-'0']++;
b[j][ch-'0']++;
c[x][y][ch-'0']++;
}
}
dfs(1,1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: