代码实现:
bool isValid(char **board, int row, int col, char c) {for (int i = 0; i < 9; i++) { // 行if (board[row][i] == c) {return false;}if (board[i][col] == c) { // 列return false;}}int startRow = (row / 3) * 3;int startCol = (col / 3) * 3;for (int i = startRow; i < startRow + 3; i++) { // 判断9方格里是否重复for (int j = startCol; j < startCol + 3; j++) {if (board[i][j] == c ) {return false;}}}return true; }bool DFS(char **board, int boardSize, int *boardColSize){for (int i = 0; i < boardSize; i++) { // 遍历行for (int j = 0; j < *boardColSize; j++) { // 遍历列if (board[i][j] != '.') {continue;}for (char c = '1'; c <= '9'; c++) {if (isValid(board, i, j, c)) {board[i][j] = c; // 放置cif (DFS(board, boardSize, boardColSize)) { // 如果找到合适一组立刻返回return true;}board[i][j] = '.'; // 回溯,撤销c}}return false; // 9个数都试完了,都不行,那么就返回false}}return true; // 遍历完没有返回false,说明找到了合适棋盘位置了 }void solveSudoku(char **board, int boardSize, int *boardColSize){DFS(board, boardSize, boardColSize); }