数独是一种逻辑游戏,目标是在9x9的网格中填入数字1到9,使得每行、每列以及每个3x3的子网格中的数字都不重复。递归和回溯是解决数独问题的常用算法。
#include <stdio.h>
#include <stdbool.h>
#define N 9
bool isValid(int board[N][N], int row, int col, int num) {
for (int x = 0; x < N; x++) {
if (board[row][x] == num || board[x][col] == num) {
return false;
}
}
int startRow = row - row % 3, startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i + startRow][j + startCol] == num) {
return false;
}
}
}
return true;
}
bool solveSudoku(int board[N][N], int row, int col) {
if (row == N - 1 && col == N) {
return true;
}
if (col == N) {
row++;
col = 0;
}
if (board[row][col] > 0) {
return solveSudoku(board, row, col + 1);
}
for (int num = 1; num <= N; num++) {
if (isValid(board, row, col, num)) {
board[row][col] = num;
if (solveSudoku(board, row, col + 1)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
void printBoard(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int main() {
int board[N][N] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (solveSudoku(board, 0, 0)) {
printBoard(board);
} else {
printf("No solution exists\n");
}
return 0;
}
通过上述代码和解释,你应该能够理解并实现一个基本的数独求解器。
领取专属 10元无门槛券
手把手带您无忧上云