#include <iostream>
using namespace std;
const int N = 15;
int arr[N][N];
bool answer;
bool check(int row, int col, int val) {
for (int i = 0; i < 9; i++) {
if (arr[row][i] == val) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (arr[i][col] == val) {
return false;
}
}
int lim_row = row / 3 * 3 + 3;
int lim_col = col / 3 * 3 + 3;
for (int i = lim_row - 3; i < lim_row; i++) {
for (int j = lim_col - 3; i < lim_col; j++) {
if (arr[i][j] == val) {
return false;
}
}
}
return true;
}
void dfs(int row, int col) {
if (col == 9) {
row++;
col = 0;
}
if (row == 9 && col == 0) {
answer = true;
return;
}
if (arr[row][col] == 0) {
for (int i = 1; i <= 9; i++) {
if (check(row, col, i)) {
arr[row][col] = i;
dfs(row, col + 1);
if (answer) {
return;
}
arr[row][col] = 0;
}
}
}
else {
dfs(row, col + 1);
}
}
int main() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cin >> arr[i][j];
}
}
dfs(0, 0);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
/*
0 9 2 4 8 1 7 6 3
4 1 3 7 6 2 9 8 5
8 6 7 3 5 9 4 1 2
6 2 4 1 9 5 3 7 8
7 5 9 8 4 3 1 2 6
1 3 8 6 2 7 5 9 4
2 7 1 5 3 8 6 4 9
3 8 6 9 1 4 2 5 7
0 4 5 2 7 6 8 3 1
*/
数独问题算法
最新推荐文章于 2024-08-04 15:38:02 发布