您的位置:首页 > Web前端 > JavaScript

DFS 2676POJSudoku数独

2015-09-24 17:02 501 查看
Sudoku

Time Limit: 2000MS Memory Limit: 65536K

Total Submissions: 16199 Accepted: 7915 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

716k 0ms

dfs枚举待填空格

每个空格 枚举1-9的数

先判断该空格是否可以填入枚举数

如果不可以填,那么返回枚举下一个

如果可以填,那么填入,接着判断下一个格可不可以填

如果下一个也可以填,那么返回true.

如果该空格所有的9个数都无法枚举,则返回false



716k 0ms

dfs枚举待填空格

每个空格 枚举1-9的数

先判断该空格是否可以填入枚举数

如果不可以填,那么返回枚举下一个

如果可以填,那么填入,接着判断下一个格可不可以填

如果下一个也可以填,那么返回true.

如果该空格所有的9个数都无法枚举,则返回false

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int col[10][10];//col[j][x]表示第j列有数x
bool row[10][10];//row[i][x]表示第i行有数x
bool grid[4][4][10];//grid[i][j][x]表示第i行第j列的中方格有数x
int  map[10][10];
struct Rest
{
int x,y;
}rest[90];//存放需要填补的空格坐标
bool dfs(int _count){
if(_count<0) return true;
int x=rest[_count].x,y=rest[_count].y;
for(int k=1;k<=9;k++){
if(col[y][k]||row[x][k]||grid[x/3][y/3][k]) continue;
map[x][y]=k;
col[y][k]=row[x][k]=grid[x/3][y/3][k]=true;
if(dfs(_count-1)) return true;
col[y][k]=row[x][k]=grid[x/3][y/3][k]=false;//如果该格所有数都不能填,回溯
}
return false;
}

int main(){
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int T,_count;
scanf("%d",&T);
while (T--){
_count=0;
memset(grid,0,sizeof(grid));
memset(col,0,sizeof(col));
memset(row,0,sizeof(row));
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
scanf("%1d",&map[i][j]);
if(0!=map[i][j]){
col[j][map[i][j]]=true;
row[i][map[i][j]]=true;
grid[i/3][j/3][map[i][j]]=true;
}
else rest[_count++]=(Rest){i,j};
}
}
dfs(_count-1);
for(int i=0;i<9;i++){
for(int j=0;j<9;j++)
cout<<map[i][j];
cout<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs poj 数独