闲来无事,用dfs写个数独计算器
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int n = 9, m = 9;
string s[10000]
bool check(int x, int y) {
bool book[20];
memset(book, 0, sizeof(book));
for (int i = x / 3 * 3; i <= x / 3 * 3 + 2; i++)
for (int j = y / 3 * 3; j <= y / 3 * 3 + 2; j++)
if (s[i][j] != '*')
if (book[s[i][j] - '0'] == 0)
book[s[i][j] - '0'] = 1;
else
return false;
memset(book, 0, sizeof(book));
for (int i = 0; i < n; i++)
if (s[i][y] != '*')
if (book[s[i][y] - '0'] == 0)
book[s[i][y] - '0'] = 1;
else
return false;
memset(book, 0, sizeof(book));
for (int i = 0; i < m; i++)
if (s[x][i] != '*')
if (book[s[x][i] - '0'] == 0)
book[s[x][i] - '0'] = 1;
else
return false;
return true;
}
bool judge() {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (s[i][j] == '*') return false;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (!check(i, j)) return false;
return true;
}
void dfs() {
if (judge()) {
printf("-----------\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%c", s[i][j]);
if ((j + 1) % 3 == 0) printf(" ");
}
printf("\n");
if ((i + 1) % 3 == 0) printf("\n");
}
exit(0);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (s[i][j] == '*') {
for (int l = 1; l <= 9; l++) {
s[i][j] = l + '0';
if (check(i, j)) dfs();
s[i][j] = '*';
}
return;
}
return;
}
int main(int argc, char const *argv[]) {
printf("请输入9×9的数独矩阵(需要填数的格子请填*):\n");
for (int i = 0; i < n; i++) cin >> s[i];
dfs();
printf("无解\n");
return 0;
}
代码演示: