数独游戏
题目链接:ybt 入门到进阶模拟赛 Day2 T4
题目大意
就要你填一个数独,保证有唯一解。
思路
直接暴力 dfs,不用剪枝优化都可以过。
代码
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
struct zb {
int x, y;
};
char a[11][11];
bool can, used[11][11][11];
int know[11][11];
queue <zb> q;
int heng[11][11], zong[11][11], blogs[11][11];
int get_kuai(int x, int y) {//求属于哪个小区间
if (x <= 3 && y <= 3) return 1;
if (x <= 3 && y <= 6) return 2;
if (x <= 3 && y <= 9) return 3;
if (x <= 6 && y <= 3) return 4;
if (x <= 6 && y <= 6) return 5;
if (x <= 6 && y <= 9) return 6;
if (x <= 9 && y <= 3) return 7;
if (x <= 9 && y <= 6) return 8;
if (x <= 9 && y <= 9) return 9;
}
void dfs(int nowx, int nowy) {
if (nowx > 9) {
can = 1;
return ;
}
if (can) return ;
if (a[nowx][nowy] != '?') {
if (nowy == 9) {
dfs(nowx + 1, 1);
}
else dfs(nowx, nowy + 1);
return ;
}
for (int i = 1; i <= 9; i++)
if (!heng[nowx][i] && !zong[nowy][i] && !blogs[get_kuai(nowx, nowy)][i]) {//不会有冲突
heng[nowx][i] = 1;
zong[nowy][i] = 1;
blogs[get_kuai(nowx, nowy)][i] = 1;
a[nowx][nowy] = i + '0';
if (nowy == 9) {
dfs(nowx + 1, 1);
}
else dfs(nowx, nowy + 1);
if (can) return ;
heng[nowx][i] = 0;
zong[nowy][i] = 0;
blogs[get_kuai(nowx, nowy)][i] = 0;
a[nowx][nowy] = '?';
}
}
int main() {
freopen("sudoku.in", "r", stdin);
freopen("sudoku.out", "w", stdout);
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
a[i][j] = getchar();
while (a[i][j] != '?' && !(a[i][j] >= '1' && a[i][j] <= '9'))
a[i][j] = getchar();
if (a[i][j] != '?') {
heng[i][a[i][j] - '0'] = 1;
zong[j][a[i][j] - '0'] = 1;
blogs[get_kuai(i, j)][a[i][j] - '0'] = 1;
}
}
}
dfs(1, 1);
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
return 0;
}
本文介绍了一种使用深度优先搜索(DFS)解决数独问题的方法,该方法无需剪枝优化即可找到唯一解。通过直接暴力搜索的方式填充数独空缺,确保了数独的有效性和唯一性。

被折叠的 条评论
为什么被折叠?



