【YbtOJ高效进阶 深搜-2】数独游戏
作者:互联网
小目录
链接
题目描述
给出一个数独,让你把它填完
样例输入
4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......
......52..8.4......3...9...5.1...6..2..7........3.....6...1..........7.4.......3.
end
样例输出
417369825632158947958724316825437169791586432346912758289643571573291684164875293
416837529982465371735129468571298643293746185864351297647913852359682714128574936
思路
每个点,只需满足与它同一行的,同一列的,同一个九宫格内的数字都不一样就可以了
那么用三个数组去存行,列,宫的就可以直接深搜了
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
bool lq[11][11], h[11][11], l[11][11], b;
int a[11][11];
char c[91];
void write() {
for(int i = 1; i <= 9; ++i)
for(int j = 1; j <= 9; ++j)
printf("%d", a[i][j]);
printf("\n");
return;
}
int get_num(int x, int y)
{
if (x <= 3) return 1 + (y - 1) / 3;
else if (x <= 6) return 4 + (y - 1) / 3;
else return 7 + (y - 1) / 3;
}
void dfs(int x, int y)
{
if(b) return;
if(y > 9) {y = 1; x++;}
if(x == 10 && y == 1) {
write();
b = 1;
return;
}
if(b) return;
if(a[x][y] != -1) {
dfs(x, y + 1);
return;
}
for(int i = 1; i <= 9; ++i)
{
if(!lq[get_num(x, y)][i] && !l[y][i] && !h[x][i]) {
a[x][y] = i;
lq[get_num(x, y)][i] = 1;
l[y][i] = 1;
h[x][i] = 1;
dfs(x, y + 1);
lq[get_num(x, y)][i] = 0;
l[y][i] = 0;
h[x][i] = 0;
a[x][y] = -1;
}
}
return;
}
int main()
{
scanf("%s", &c);
while(c[0] != 'e') {
memset(l, 0, sizeof(l));
memset(h, 0, sizeof(h));
memset(lq, 0, sizeof(lq));
for(int i = 0; i < 81; ++i)
{
b = 0;
if(c[i] != '.') {
a[1 + i / 9][i % 9 + 1] = c[i] - 48;
lq[get_num(1 + i / 9, i % 9 + 1)][c[i] - 48] = 1;
l[i % 9 + 1][c[i] - 48] = 1;
h[1 + i / 9][c[i] - 48] = 1;
}
else a[1 + i / 9][i % 9 + 1] = -1;
}
dfs(1, 1);
scanf("%s", c);
}
}
标签:11,return,进阶,int,YbtOJ,.....,lq,include,数独 来源: https://blog.csdn.net/LTH060226/article/details/112389870