您的位置:首页 > 其它

Sudoku(POJ 2676)

2015-01-30 18:47 211 查看
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


题解:dfs+剪枝

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int board[9][9];
int res[9][9];
int r[9][10],c[9][10],block[9][10];
bool flag;
void solve(int i,int j){
if(flag) return;
bool temp;
temp=false;
for(i;i<9;i++){
for(j=0;j<9;j++){
if(!board[i][j]){
temp=true;
break;
}
}
if(temp) break;
}
if(i==9&&j==9){
flag=true;
for(int a=0;a<9;a++){
for(int b=0;b<9;b++){
res[a][b]=board[a][b];
}
}
return;
}
int pos;
pos=(i/3)*3+j/3;
for(int a=1;a<10;a++){
if(!r[i][a]&&!c[j][a]&&!block[pos][a]){
board[i][j]=a;
r[i][a]=1;
c[j][a]=1;
block[pos][a]=1;
solve(i,j); //////////////
board[i][j]=0;
r[i][a]=0;
c[j][a]=0;
block[pos][a]=0;
}
}
}
int main(){
int ncase;
cin>>ncase;
while(ncase--){
flag=false;
memset(r,0,sizeof(r));
memset(c,0,sizeof(c));
memset(block,0,sizeof(block));
int pos;
char ch;
for(int a=0;a<9;a++){
cin.get();
for(int b=0;b<9;b++){
ch=cin.get();
board[a][b]=ch-'0';
r[a][board[a][b]]=1;
c[b][board[a][b]]=1;
pos=(a/3)*3+b/3;
block[pos][board[a][b]]=1;
}
}
solve(0,0);
for(int a=0;a<9;a++){
for(int b=0;b<9;b++){
cout<<res[a][b];
}
cout<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: