回溯所有答案

时间:2015-05-08 15:18:52

标签: c recursion sudoku backtracking

我这里有这个代码。当您解决数独问题时,它可以正常工作。

int solveBoard(int board[SIZE][SIZE], int rowPos, int colPos) {
    int newValueToCheck, oldRowPos, oldColPos;
    if (rowPos == SIZE) return 1;
    if (board[rowPos][colPos] != 0) {
        if (colPos == SIZE - 1) {
            rowPos++;
            colPos = 0;
        } else colPos++;
        if (solveBoard(board, rowPos, colPos) == 1) return 1;
        return 0;
    } for (newValueToCheck = 1; newValueToCheck <= SIZE; newValueToCheck++)
        if (checkBoard(board, newValueToCheck, rowPos, colPos) == 1) {
            board[rowPos][colPos] = newValueToCheck;
            oldRowPos = rowPos; 
            oldColPos = colPos;
            if (colPos == SIZE - 1) {
                rowPos++;
                colPos = 0;
            } else colPos++;
            if (solveBoard(board, rowPos, colPos) == 1) return 1;
            rowPos = oldRowPos;
            colPos = oldColPos;
            board[rowPos][colPos] = 0;
        }
    return 0;
}

唯一的问题是,我想得到所有可能的答案。我将如何修改它并获得所有可能的答案。

1 个答案:

答案 0 :(得分:2)

找不到解决方案时,不要回溯搜索。因此,在您尝试新值的地方进行简单的递归调用并忽略其返回值:

solveBoard(board, rowPos, colPos);

然后你在递归尾部的每个解决方案:

if (rowPos == SIZE) printSolution(); return 1;