Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 9723 | Accepted: 4814 | 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
题目链接:http://poj.org/problem?id=2676
解法类型:DFS
解题思路:DFS,逐行搜索,记录为0的位置,一次标记,判断每行,每列,和每个小数独是否满足.
算法实现:
#include<stdio.h>
#include<memory.h>
int DFS(int b,int cur);
int judge(int x,int y,int num);
const int MAXN=10;
char map[MAXN][MAXN];
int map_zero[MAXN*MAXN][2],vis_x[MAXN][MAXN],vis_y[MAXN][MAXN];
int main()
{
// freopen("in.txt","r",stdin);
int i,j,n,tot,t,k;
scanf("%d",&n);
while(n--)
{
tot=0,k=0;
memset(vis_x,0,sizeof(vis_x));
memset(vis_y,0,sizeof(vis_y));
for(i=0;i<9;i++){
scanf("%s",map[i]);
for(j=0;j<9;j++)
if(map[i][j]!='0'){ //标记数字
tot++;
t=map[i][j]-'1';
vis_x[i][t]=1;
vis_y[j][t]=1;
}
else {
map_zero[k][0]=i; //存储零的坐标位置
map_zero[k++][1]=j;
}
}
if(DFS(0,tot))
for(i=0;i<9;i++)
printf("%s\n",map[i]);
}
return 0;
}
int DFS(int b,int cur)
{
if(cur==81)return 1; //search succeed
int x=map_zero[b][0],y=map_zero[b][1];
for(int j=0;j<9;j++)
{
if(!vis_x[x][j] && (!vis_y[y][j]) && judge(x,y,j)){ //判断有没有重复
map[x][y]=j+'1';
vis_x[x][j]=vis_y[y][j]=1;
if(DFS(b+1,cur+1))return 1; //search succeed 跳出
map[x][y]='0';
vis_x[x][j]=vis_y[y][j]=0;
}
}
return 0;
}
int judge(int x,int y,int a) //判断在小格子里能否放置
{
int i,j;
for(i=x/3*3;i<=x/3*3+2;i++)
for(j=y/3*3;j<=y/3*3+2;j++)
if(map[i][j]=='1'+a)return 0;
return 1;
}