# poj 2676 Sudoku （基础DFS）

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

#include <cstdio>
#include <cstring>
int a[10][10];
char s[10][10];
bool p;
bool ok(int k,int x,int y)  //判断数字k是否满足条件
{
for(int i=0;i<9;i++)    //保证每行不出现重复数字
if(a[x][i]==k)
return false;   //保证每列不出现重复数字
for(int i=0;i<9;i++)
if(a[i][y]==k)
return false;
x=x-x%3,y=y-y%3;
for(int i=x;i<x+3;i++)  //保证每个小九宫格里不出现重复数字
for(int j=y;j<y+3;j++)
{
if(a[i][j]==k)
return false;
}
return true;
}
void dfs(int x,int y)   //x,y是当前格子的横纵坐标
{
if(p||x==9)         //x为9时说明格子已填满，p标记搜索成功，返回
{
p=true;
return;
}
while(a[x][y])      //当格子里有数字时改变坐标直道得到空格子
{
if(y==8)
{
x++;
y=0;
}
else
y++;
if(x==9)
{
p=true;
return;
}
}
for(int k=1;k<=9;k++)   //枚举九个数字，判断这些数字是否能填入当前格子
{
if(ok(k,x,y))
{
a[x][y]=k;
if(y==8)
dfs(x+1,0);
else
dfs(x,y+1);
if(p)
return;
a[x][y]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
p=false;
for(int i=0;i<9;i++)
{
scanf("%s",s[i]);
for(int j=0;j<9;j++)
a[i][j]=s[i][j]-'0';
}
dfs(0,0);
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
printf("%d",a[i][j]);
printf("\n");
}
}
return 0;
}

#### POJ 2676 Sudoku (数独 DFS)

2015-02-10 09:11:41

#### poj-2676 Sudoku

2015-08-20 14:31:22

#### poj 2676 Sudoku

2016-08-09 13:29:00

#### POJ Sudoku 数独填数（深搜）

2013-10-03 14:01:47

#### POJ3074 sudoku数独

2017-10-10 15:07:30

#### POJ3435 Sudoku Checker【谜题+数独】

2016-08-09 09:09:16

#### POJ Sudoku 【DFS】

2018-06-05 15:08:04

#### POJ 3076 Sudoku (DLX解数独)

2015-10-02 10:36:20

#### POJ 3435 Sudoku Checker

2014-08-02 23:16:07

#### POJ 2676 Sudoku（DFS）

2015-08-18 15:29:30