Language:
Sudoku
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 |
解题思路,从左上角开始试着填数,这个数应该是该行、该列和方块中都未出现的数字(因此,需要判断一个格子是否能填某个数),这个方法叫做剪枝,深度优先搜索直到填满所有的数。
AC代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
int a[10][10];
char s[10][10];
//下标都是从0到8
//判断(x,y)处能否放置k
bool flag;
bool ok(int k,int x,int y)
{
for(int i=0;i<9;i++){
if(a[i][y]==k) return false;
}
for(int j=0;j<9;j++){
if(a[x][j]==k) return false;
}
int u=x-x%3,v=y-y%3;
for(int i=u;i<u+3;i++){
for(int j=v;j<v+3;j++){
if(a[i][j]==k) return false;
}
}
return true;
}
//从当前点(x,y)开始深度优先搜索
void dfs(int x,int y)
{
//flag是成功的标志,而放置数字是按行从上到下开始,因此x==9也是成功的标志
if(flag||x==9){
flag=true;
return;
}
//(x,y)处已放置数字,放置下一个格子
while(a[x][y]){
if(y==8){
x++;
y=0;
}
else y++;
if(x==9){
flag=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(flag) return;
a[x][y]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
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';
}
}
flag=false;
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;
}