Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 21955 | Accepted: 10412 | 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
题意:数独填数字,每一行,每一列,每一块1到9数字不能重复,求解。dfs,,把每个需要填的位置记录下来,dfs结束条件就为填的位置都填完了就输出,注意返回条件很重要,原来落一个返回,结果没有输出了:)
代码:
#include<stdio.h>
#include<vector>
#include<string.h>
using namespace std;
bool row[10][10];
bool cal[10][10];
bool kuai[10][10];
int a[10][10],n;
struct dian
{
int i,j;
}d;
vector<dian>f;
bool flag;
void dfs(int k)
{
if(k==n)
{
flag=true;
for(int o=0;o<9;o++)
{
for(int u=0;u<9;u++)
{
printf("%d",a[o][u]);
}
printf("\n");
}
return;
}
for(int i=1;i<=9;i++)
{
dian g=f[k];
int p=(g.i/3)*3+g.j/3+1;//找到对应位置是第几块,至于为什么画个图算一下很容易看出来
if(row[g.i][i]==0&&cal[g.j][i]==0&&kuai[p][i]==0)
{
row[g.i][i]=cal[g.j][i]=kuai[p][i]=1;
a[g.i][g.j]=i;
dfs(k+1);
if(flag)return;//最关键是这里,如果不及时返回则找到的答案就会前功尽弃
row[g.i][i]=cal[g.j][i]=kuai[p][i]=0;
a[g.i][g.j]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
f.clear();
memset(cal,0,sizeof(cal));
memset(row,0,sizeof(row));
memset(kuai,0,sizeof(kuai));
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
scanf("%1d",&a[i][j]);
if(a[i][j])
{
row[i][a[i][j]]=1;
cal[j][a[i][j]]=1;
int k=(i/3)*3+j/3+1;
kuai[k][a[i][j]]=1;
}
else
{
d.i=i;
d.j=j;
f.push_back(d);
}
}
}
flag=false;
n=f.size();
dfs(0);//这里注意要从0开始,因为vector里是从0开始的,否则就会少点
}
}