【问题标题】:How to extract base-case returns from recursive function?如何从递归函数中提取基本情况返回?
【发布时间】:2016-05-05 03:42:41
【问题描述】:

这是我解决N-Queens 问题的递归函数,该问题要求找出棋盘上皇后的配置数量,以使它们不能相互攻击。在validPosition 的帮助下,此函数成功地为每个 N 值输入了基本情况(curRow == N) 的正确次数。但是,我不清楚如何提取此信息。如果函数进入基本情况 10 次,则此函数应返回 10。

但是,让它返回布尔值是在其递归调用上进行条件分支的技术。是否有一种干净且一致的方法既可以正确输入基本案例的次数,又可以将该信息成功传播到根函数调用并将其返回给调用者?

static boolean findNQueensSolutions(int N, int curRow, int[][] board, int result) {

    if (curRow == N) {
        return true;
    }

    for (int curCol = 0; curCol < N; curCol++) {

        if (validPosition(board, curRow, curCol, N)) {

            board[curRow][curCol] = 1;

            if (findNQueensSolutions(N, curRow + 1, board, result)) {
                return true;

            }

            board[curRow][curCol] = 0;
        }

    }
    return false;
}

【问题讨论】:

    标签: java recursion n-queens


    【解决方案1】:

    您需要收集有关成功职位的信息,如下所示:

    static int findNQueensSolutions(int N, int curRow, int[][] board) {
        if (curRow == N)
            return 1; // found 1 position
    
        int result = 0; // found 0 positions yet
        for (int curCol = 0; curCol < N; curCol++)
            if (validPosition(board, curRow, curCol, N)) {
                board[curRow][curCol] = 1;
                result += findNQueensSolutions(N, curRow + 1, board); // do not return immediately, maybe there are more?
                board[curRow][curCol] = 0;
            }
        return result;
    }
    

    【讨论】:

    • 这是我最初的方法,但我要么得到了一个荒谬的高结果,要么 1. 令人讨厌的是,我无法确定我犯了什么错误,但它现在有效。谢谢!
    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 2012-03-31
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多