poj Sudoku

来源:互联网 发布:hishop云商城源码 编辑:程序博客网 时间:2024/05/20 03:41

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

1103000509002109400000704000300502006060000050700803004000401000009205800804000107

Sample Output

143628579572139468986754231391542786468917352725863914237481695619275843854396127

//数独:同行同列和小的3*3块内不能重复

// 该题不同之处在于,对于每一次深搜需要判断是否回溯
// 通过一列一列(也可以通过一行一行)来进行搜索
// 关键在于如何对9个 3*3 的小方块进行判断及回溯的判断 
// 对于坐标为(i,j)的来说,所处小方块下标为 p= 3*(i/3)+j/3 小方块从左到右,从上到下,从0开始依次标号 
//  回溯:当y==9,说明搜索完毕,返回1;每次填空若不能找到返回0 ; 
 
#include<stdio.h>
#include<string.h>


char a[10][10];
int row[10][10],col[10][10],part[10][10];// 标记行、列和3*3的小块 


int dfs(int x,int y)
{

if(y == 9)
{
/*for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
printf("%d",a[i][j]);
printf("\n");
} */
return 1;
}
int flag=0;

if(x == 9 )
{
if(dfs(0,y+1))
return 1;
else return 0;
}

if(a[x][y]==0)
{   
int p=3*(x/3)+y/3;
for(int i=1;i<10;i++)
{
if(row[x][i]==0 && col[y][i]==0 && part[p][i]==0)
{
a[x][y]=i;
row[x][i]=1;
col[y][i]=1;
part[p][i]=1;
if(x==9)
{
flag=dfs(0,y+1);
}
else flag=dfs(x+1,y);

if(flag==0)
{
a[x][y]=0;
row[x][i]=0;
col[y][i]=0;
part[p][i]=0;
}
else return 1;
}
}
return 0;
}
else 
{
if(x==9)
{
flag=dfs(0,y+1);
}
else
{
flag=dfs(x+1,y);
  }
  if(flag)
return 1;
else return 0;
}
}


int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(row,0,sizeof(row));
memset(col,0,sizeof(col));
memset(part,0,sizeof(part));
int num,p;
for(int i=0;i<9;i++)
{
scanf("%s",a+i);
for(int j=0;j<9;j++)
{
a[i][j]=a[i][j]-'0';
if(a[i][j])
{
p=3*(i/3)+j/3;
row[i][ a[i][j]  ]=1;
col[j][ a[i][j]  ]=1;
part[p][ a[i][j] ]=1; 
}

}
}
/* printf("\n");
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\n");
*/
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;
}
0 0