HDU - 5547 Sudoku(数独搜索)

Description

Yi Sima was one of the best counselors of Cao Cao. He likes to play a funny game himself. It looks like the modern Sudoku, but smaller.

Actually, Yi Sima was playing it different. First of all, he tried to generate a 4×4 board with every row contains 1 to 4, every column contains 1 to 4. Also he made sure that if we cut the board into four 2×2 pieces, every piece contains 1 to 4.

Then, he removed several numbers from the board and gave it to another guy to recover it. As other counselors are not as smart as Yi Sima, Yi Sima always made sure that the board only has one way to recover.

Actually, you are seeing this because you've passed through to the Three-Kingdom Age. You can recover the board to make Yi Sima happy and be promoted. Go and do it!!!

Input

The first line of the input gives the number of test cases, T(1≤T≤100). T test cases follow. Each test case starts with an empty line followed by 4 lines. Each line consist of 4 characters. Each character represents the number in the corresponding cell (one of '1', '2', '3', '4'). '*' represents that number was removed by Yi Sima.

It's guaranteed that there will be exactly one way to recover the board.

Output

For each test case, output one line containing Case #x:, where x is the test case number (starting from 1). Then output 4 lines with 4 characters each. indicate the recovered board.
Sample Input

****

*
*
*
*
**
***
*
**
Sample Output
Case #: Case #: Case #:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5547

The 2015 China Collegiate Programming Contest

 ***********************************************

分析:一道比较简单的数独题目,这里简化了问题,变成了一个4*4的图,然后小图变成了2*2的图,这里问题就简洁了很多。

地图辣么小,直接枚举每一个点就行了。

从左上角开始,一直枚举到右下角,然后输出了就行了。

每次遇到一个“*”我们就枚举他变成1,2,3,4然后判断是否合法,如果合法就进行下一个点,否则回溯。

 #include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<time.h>
#include<stack>
using namespace std;
#define N 120000
#define INF 0x3f3f3f3f char a[][]; int judge(int x,int y)
{
int i,j; for(i=;i<;i++)///列判断,不能有相同的数字
if(a[x][i]==a[x][y]&&i!=y)
return ; for(i=;i<;i++)///行判断,不能有相同的数字
if(a[i][y]==a[x][y]&&i!=x)
return ; int row=x;
int col=y;
if(x%==)x-=;///找到小矩阵的左上角
if(y%==)y-=; for(i=x;i<=x+;i++)///小矩阵判断,不能有相同的数字
for(j=y;j<=y+;j++)
if(a[i][j]==a[row][col]&&i!=row&&j!=col)
return ; return ;
} void dfs(int x)///回溯dfs
{
int i,j; if(x==*)///如果遍历了所有点,就输出最终图形
{
for(i=;i<;i++)
{
for(j=;j<;j++)
printf("%c", a[i][j]);
printf("\n");
}
return ;
} int row=x/;///行的计算方法
int col=x%;///列的计算方法 if(a[row][col]=='*')
{
for(j=;j<=;j++)///枚举4个数字
{
a[row][col]=j+'';
if(judge(row,col))///如果当前这个点符合规则
dfs(x+);///进行下一步
a[row][col]='*';///记得要取消标记。(深搜尝试问题,涉及回溯)
}
}
else///如果不是,跳过,进行下一步
dfs(x+);
} int main()
{
int T,k=,i; scanf("%d", &T); while(T--)
{
for(i=;i<;i++)
scanf("%s", a[i]); printf("Case #%d:\n", k++); dfs();
}
return ;
}
上一篇:Python高级——多任务编程之线程


下一篇:python多任务【一】- 线程:同步|互斥锁|死锁