link
解题思路
话说我很喜欢数独欸
暴搜尝试一个地方可以填什么数
Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
using namespace std;
string s;
int c, a[15][15], h, x[15][15], y[15][15], g[15][15];
int check(int x, int y) {
//九宫格编号从左到右从上到下 1~9
if (x <= 3) {
if (y <= 3) return 1;
if (y > 3 && y <= 6) return 2;
return 3;
}
if (x > 3 && x <= 6) {
if (y <= 3) return 4;
if (y > 3 && y <= 6) return 5;
return 6;
}
if (y <= 3) return 7;
if (y > 3 && y <= 6) return 8;
return 9;
}
void dfs(int xx,int yy) {
if (h) return;//是否找到过解
if (xx > 9) {
//找到解
for (int i = 1; i <= 9; i++)
for (int j = 1; j <= 9; j++)
printf("%d", a[i][j]);
h = 1;
return;
}
if (a[xx][yy]) {
//如果已有固定的数
if (yy < 9)
dfs(xx, yy + 1);
else dfs(xx + 1, 1);
return;
}
for (int i = 1; i <= 9; i++) {
if (!x[xx][i] && !y[yy][i] && !g[check(xx, yy)][i]) {
//尝试填数
x[xx][i] = y[yy][i] = g[check(xx, yy)][i] = 1;
a[xx][yy] = i;
if (yy < 9)
dfs(xx, yy + 1);
else dfs(xx + 1, 1);
a[xx][yy] = 0;
x[xx][i] = y[yy][i] = g[check(xx, yy)][i] = 0;
}
}
}
int main() {
cin>>s;
while (s != "end") {
h = 0;
memset(a, 0, sizeof(a));
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
memset(g, 0, sizeof(g));
for (int i = 1; i <= 9; i++)
for (int j = 1; j <= 9; j++)
{
c = (i - 1) * 9 + j;
if (s[c - 1] >= '0' && s[c - 1] <= '9') {
a[i][j] = s[c - 1] - '0';
x[i][a[i][j]] = y[j][a[i][j]] = g[check(i, j)][a[i][j]] = 1;//记录行、列、九宫格
}
}
dfs(1, 1);
printf("\n");
cin>>s;
}
}