Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 12075 | Accepted: 6026 | 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
题意:数独问题,当有多种方案时任意输出一种; 思路:回溯法,用三个数组row[][],col[][],square[][]维护某个数是否能被填充,在未填充的空格里尝试着放一个数,继续递归,当发生冲突时就回溯,更改已做的标记;
#include<stdio.h>
#include<string.h>
int map[][];
bool row[][];//row[i][x] 表示第i行x是否出现过;
bool col[][];//col[j][x] 表示第j行x是否出现过;
bool square[][];//square[k][x] 表示第k个方格x是否出现过; bool dfs(int x, int y)
{ if(x == )
return true;//递归边界;
bool flag = false; if(map[x][y])//如果map[x][y]已经填了数字,确定向下递归的方向;
{
if(y == )
flag = dfs(x+,);
else
flag = dfs(x,y+); if(flag)
return true;
else return false;
}
else
{
int k = *((x-)/) + (y-)/+;
for(int i = ; i <= ; i++)
{
if(!row[x][i] && !col[y][i] && !square[k][i])
{
map[x][y] = i;//找到合适的i填充; row[x][i] = true;
col[y][i] = true;
square[k][i] = true;
//继续递归
if(y == )
flag = dfs(x+,);
else flag = dfs(x,y+); if(flag)
return true;
else //回溯,修改已作的标记
{
map[x][y] = ; row[x][i] = false;
col[y][i] = false;
square[k][i] = false;
}
}
}
}
return false;
}
int main()
{
int t;
char s[];
scanf("%d",&t);
while(t--)
{
memset(row,false,sizeof(row));
memset(col,false,sizeof(col));
memset(square,false,sizeof(square));
for(int i = ; i <= ; i++)
{
scanf("%s",s);
for(int j = ; j < ; j++)
{
map[i][j+] = s[j]-'';
if(map[i][j+])
{
int k = *((i-)/) + j/+;
row[i][ map[i][j+] ] = true;
col[j+][ map[i][j+] ] = true;
square[k][ map[i][j+] ] = true;
}
}
}
dfs(,);
for(int i = ; i <= ; i++)
{
for(int j = ; j <= ; j++)
printf("%d",map[i][j]);
printf("\n");
}
}
return ;
}