数独游戏的规则是这样的:在一个9x9的方格中,你需要把数字1-9填写到空格当中,并且使方格的每一行和每一列中都包含1-9这九个数字。同时还要保证,空格中用粗线划分成9个3x3的方格也同时包含1-9这九个数字。比如有这样一个题,大家可以仔细观察一下,在这里面每行、每列,以及每个3x3的方格都包含1-9这九个数字。
例题:
答案:
Input
本题包含多组测试,每组之间由一个空行隔开。每组测试会给你一个 9*9 的矩阵,同一行相邻的两个元素用一个空格分开。其中1-9代表该位置的已经填好的数,问号(?)表示需要你填的数。
Output
对于每组测试,请输出它的解,同一行相邻的两个数用一个空格分开。两组解之间要一个空行。
对于每组测试数据保证它有且只有一个解。
对于每组测试数据保证它有且只有一个解。
Sample Input
7 1 2 ? 6 ? 3 5 8
? 6 5 2 ? 7 1 ? 4
? ? 8 5 1 3 6 7 2
9 2 4 ? 5 6 ? 3 7
5 ? 6 ? ? ? 2 4 1
1 ? 3 7 2 ? 9 ? 5
? ? 1 9 7 5 4 8 6
6 ? 7 8 3 ? 5 1 9
8 5 9 ? 4 ? ? 2 3
Sample Output
7 1 2 4 6 9 3 5 8
3 6 5 2 8 7 1 9 4
4 9 8 5 1 3 6 7 2
9 2 4 1 5 6 8 3 7
5 7 6 3 9 8 2 4 1
1 8 3 7 2 4 9 6 5
2 3 1 9 7 5 4 8 6
6 4 7 8 3 2 5 1 9
8 5 9 6 4 1 7 2 3
PS:处理字符需谨慎!!!(因为这个一直TLE。。。。。。。。。。。
#include<cstdio>
#include<cstring>
#include<stack>
#include<vector>
#include<queue>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int oo = 1e9+7;
const int maxn = 1e6+7;
typedef long long LL;
struct da
{
int x, y;
} as[1212];/**<存放需要填数的格子的位置 */
char str[20];
int maps[20][20], ok, cnt;
int judge(int num, int cur)/**< 判断num这个数字能不能填 */
{
int i, j;
for(i = 0; i < 9; i++)/**< 判断行和列是否能填这个数 */
{
if(maps[as[cur].x][i] == num || maps[i][as[cur].y] == num) return 0;
}
int x = as[cur].x/3*3;/**< 求出当前位置所属的3*3的格子的行列范围*/
int y = as[cur].y/3*3;
for(i = 0; i < 3; i++)/**< 判断3*3的个子是否能填这个数*/
for(j = 0; j < 3; j++)
if(maps[i+x][j+y] == num) return 0;
return 1;
}
void dfs(int x)
{
int i, j;
if(x == cnt)///所有的格子填完了
{
ok = 1;
for(i = 0; i < 9; i++)
{
for(j = 0; j < 8; j++)
printf("%d ", maps[i][j]);
printf("%d\n", maps[i][8]);
}
return ;
}
for(i = 1; i <= 9; i++)
{
if(judge(i, x) && !ok)/**< !ok条件判断能节省几倍的时间 (只能标记只包含一种填法的)*/
{
maps[as[x].x][as[x].y] = i;
dfs(x+1);
maps[as[x].x][as[x].y] = 0;
}
}
// return ;
}
int main()
{
int i, j, cas=0, k;
while(scanf("%s", str)!=EOF)///数据的读入很恶心。。。。
{
ok = cnt = k = 0;
memset(maps, 0, sizeof(maps));
if(str[0] == '?')
{
as[cnt].x = 0;
as[cnt].y = 0;
cnt++;
}
if(str[0] >= '0' && str[0] <= '9') maps[0][0] = str[0]-'0';
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
if(i == 0 && j == 0) continue;
scanf("%s", str);
if(str[0] == '?')
{
as[cnt].x = i;
as[cnt].y = j;
cnt++;
}
else maps[i][j] = str[0]-'0';
}
}
if(cas++) printf("\n");
dfs(0);
}
return 0;
}
)