|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
int sudoku[9][9];
|
|
|
|
|
|
//判断行
|
|
|
int in_row(int row, int num) {
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
if (sudoku[row][i] == num) {
|
|
|
return 1;
|
|
|
}
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
//判断列
|
|
|
int in_col(int col, int num) {
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
if (sudoku[i][col] == num) {
|
|
|
return 1;
|
|
|
}
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
//判断宫
|
|
|
int in_box(int row, int col, int num) {
|
|
|
int box_row = row / 3 * 3;
|
|
|
int box_col = col / 3 * 3;
|
|
|
for (int i = box_row; i < box_row + 3; i++) {
|
|
|
for (int j = box_col; j < box_col + 3; j++) {
|
|
|
if (sudoku[i][j] == num) {
|
|
|
return 1;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
|
|
|
int is_valid(int row, int col, int num) {
|
|
|
return !in_row(row, num) && !in_col(col, num) && !in_box(row, col, num);
|
|
|
}
|
|
|
|
|
|
|
|
|
int solve_sudoku(int row, int col) {
|
|
|
if (row == 9) {
|
|
|
return 1;
|
|
|
}
|
|
|
if (col == 9) { // 行已经填完,转到下一行
|
|
|
return solve_sudoku(row + 1, 0);
|
|
|
}
|
|
|
if (sudoku[row][col] != 0) { // 当前格子已经有数字,转到下一个格子
|
|
|
return solve_sudoku(row, col + 1);
|
|
|
}
|
|
|
for (int num = 1; num <= 9; num++) { //枚举<E69E9A>
|
|
|
if (is_valid(row, col, num)) {
|
|
|
sudoku[row][col] = num;
|
|
|
if (solve_sudoku(row, col + 1)) {
|
|
|
return 1;
|
|
|
}
|
|
|
sudoku[row][col] = 0; // 回溯
|
|
|
}
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
int main() {
|
|
|
// 输入数独数组
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
for (int j = 0; j < 9; j++) {
|
|
|
scanf("%d", &sudoku[i][j]);
|
|
|
}
|
|
|
}
|
|
|
// 求解数独
|
|
|
if (solve_sudoku(0, 0)) {
|
|
|
// 输出求解结果
|
|
|
for (int i = 0; i < 9; i++) {
|
|
|
for (int j = 0; j < 9; j++) {
|
|
|
printf("%d ", sudoku[i][j]);
|
|
|
}
|
|
|
printf("\n");
|
|
|
}
|
|
|
} else {
|
|
|
printf("No solution!\n");
|
|
|
}
|
|
|
return 0;
|
|
|
}
|
|
|
}
|