POJ 2676 Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 17627 | Accepted: 8538 | 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
我的思路错误之处:我本来只设置了两个二维bool数组表示每行9个数字和每列9个数字,是否用过,再深搜填写9个方格,可是发现,深搜填写每个方格是很难写的。
正解:开是三个二维bool数组,分别表示每列每行每个大方格的数字的使用情况。
读入时注意数字是连起来的。
/*----------------正确代码-------------------------*/
#include<iostream>
using namespace std;
#include<cstdio>
#include<cstring>
#define N 15
char duru[N];
int jz[N][N];
bool flag=false,flagfg[N][N],flaghang[N][N],flaglie[N][N];
inline void input()
{
for(int i=;i<=;++i)
{
scanf("%s",duru+);/*注意读入的数字之间没有空格*/
for(int j=;j<=;++j)
{
jz[i][j]=duru[j]-'';
if(jz[i][j]==) continue;
int k=*((i-)/)+(j-)/+;
flagfg[k][jz[i][j]]=true;
flaghang[i][jz[i][j]]=true;
flaglie[j][jz[i][j]]=true;
}
}
}
void output()
{
for(int i=;i<=;++i)
{
for(int j=;j<=;++j)
printf("%d",jz[i][j]);
printf("\n");
}
}
void dfs(int x,int y)
{
if(x==)
{
flag=true;
return;
}
if(jz[x][y])
{
if(y==)
dfs(x+,);
else dfs(x,y+);
if(flag) return;
}
else {
int k=*((x-)/)+(y-)/+;
for(int i=;i<=;++i)
{
if(!flaghang[x][i]&&!flaglie[y][i]&&!flagfg[k][i])
{/*枚举符合三个条件的i*/
jz[x][y]=i;
flaghang[x][i]=true;
flaglie[y][i]=true;
flagfg[k][i]=true;
if(y==)
dfs(x+,);
else dfs(x,y+);
if(flag) return;
jz[x][y]=;/*回溯*/
flaghang[x][i]=false;
flaglie[y][i]=false;
flagfg[k][i]=false; }
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
input();
dfs(,);
output();
memset(jz,,sizeof(jz));
memset(flagfg,false,sizeof(flagfg));
memset(flaghang,false,sizeof(flaghang));
memset(flaglie,false,sizeof(flaglie));
flag=false;
}
return ;
}