在C语言中解数独有多种方法,包括穷举法、回溯法、递归法以及基于图的结构等。下面我将介绍一种基于回溯法的简单实现方法。
回溯法解数独
回溯法是一种试探性的解决问题的方法,当尝试一种可能的解时,如果发现该解不符合条件,就退回一步,尝试其他的可能性。这种方法适用于数独这种约束满足问题。
```c
include include define SIZE 9 bool isValid(int board[SIZE][SIZE], int num, int pos) { int row = pos / SIZE; int col = pos % SIZE; // Check row for (int i = 0; i < SIZE; i++) { if (board[row][i] == num) { return false; } } // Check column for (int i = 0; i < SIZE; i++) { if (board[i][col] == num) { return false; } } // Check box int boxRow = row / 3; int boxCol = col / 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[boxRow * 3 + i][boxCol * 3 + j] == num) { return false; } } } return true; } bool solveSudoku(int board[SIZE][SIZE]) { int pos = -1; for (int i = 0; i < SIZE * SIZE; i++) { if (board[i / SIZE][i % SIZE] == 0) { pos = i; break; } } if (pos == -1) { return true; // Puzzle solved } for (int num = 1; num <= 9; num++) { if (isValid(board, num, pos)) { board[pos / SIZE][pos % SIZE] = num; if (solveSudoku(board)) { return true; } board[pos / SIZE][pos % SIZE] = 0; // Backtrack } } return false; // Trigger backtracking } void printBoard(int board[SIZE][SIZE]) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d ", board[i][j]); } printf("\n"); } } int main() { int board[SIZE][SIZE] = { {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)) { printBoard(board); } else { printf("No solution found.\n"); } return 0; } ``` 代码说明 检查在数独的某个位置是否可以放置某个数字。 使用回溯法递归isValid函数:
solveSudoku函数: