简体   繁体   English

回溯所有答案

[英]Backtracking all answers

I have this code here. 我在这里有这段代码。 It works fine when you're solving for a solution to a sudoku problem. 当您要解决数独问题的解决方案时,它可以正常工作。

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;
}

Only thing is, I'd like to get all possible answers. 唯一的是,我想获得所有可能的答案。 How will I modify this and get all the possible answers. 我将如何修改它并获得所有可能的答案。

Don't backtrack the search when a solution has been found. 找到解决方案后,请勿回溯搜索。 So, make a simple recursive call at the place you try new values and ignore its return value: 因此,在尝试新值并忽略其返回值的地方进行简单的递归调用:

solveBoard(board, rowPos, colPos);

and then you every solution at the tail of the recursion: 然后您在递归的末尾找到了每个解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM