【问题标题】:javascript recursive function does not stop executionjavascript递归函数不会停止执行
【发布时间】:2019-05-10 02:47:54
【问题描述】:

在我的进度函数内部,它将到达递归的基础,但我期望返回的值不会改变。

let graph = [[1,1,1],[1,1,1,],[1,1,1]]

function findPath(graph){
    function progress(row, col){
        if(row == graph.length-1 && graph[row][col]== 1) {
            console.log('makes it here but does not return true !?')
            return true;
        } 

        //check right
        if(graph[row][col+1] == 1) {
            graph[row][col] = 2
            progress(row, col+1);
        }

        // check left 
        if(graph[row][col-1] == 1) {
            graph[row][col] = 2
            progress(row, col-1);
        }

        // check down
        if(graph[row+1][col] == 1){
            graph[row][col] = 2
            progress(row+1, col)
        }  
    }

    for(let i = 0; i < graph[0].length; i++) {
        if(graph[0][i] == 1) {
            if(progress(0, i)) {
                return true;
            }
        }
    }

    return false;
}

console.log(findPath(graph))

这应该返回 true,它满足条件(记录文本)但随后继续移动,并且始终返回 false。

【问题讨论】:

  • 注意,你需要在每次递归调用progress()之前添加一个return
  • 我猜1 标志着沿路径的有效“步骤”?而不是 all 1s 的图表,也许您应该显示一些其他输入及其预期输出?

标签: javascript recursion


【解决方案1】:

好的,递归与堆栈一起工作,每个调用都被堆栈,并且在所有其他堆栈之后的调用完成后继续执行。

喜欢:

call1 -&gt; call2 -&gt; call3 -&gt; callN

在到达最后一个调用 (callN) 后,所有的调用将被从后向前拆包。

你只是在最后一次调用时返回 true,但是当函数调用被 unstacked 时这个值会丢失

换句话说,对于您的示例,您需要始终从进度函数返回值。

我尝试调整您的代码以更好地工作:

let graph = [[1,1,1],[1,1,1,],[1,1,1]]

function findPath(graph){
    function progress(row, col){
        if(row == graph.length-1 && graph[row][col]== 1) {
            return true;
        } 

        //check right
        if(graph[row][col+1] == 1) {
            graph[row][col] = 2
            var right = progress(row, col+1);
        }

        // check left 
        if(graph[row][col-1] == 1) {
            graph[row][col] = 2
            var left = progress(row, col-1);
        }

        // check down
        if(graph[row+1][col] == 1){
            graph[row][col] = 2
            var down = progress(row+1, col)
        }

        // propagate result
        return (right || left || down)
    }

    for(let i = 0; i < graph[0].length; i++) {
        if(graph[0][i] == 1) {
            if(progress(0, i)) {
                return true;
            }
        }
    }

    return false;
}

console.log(findPath(graph))

我只关注递归部分,而不是它本身的问题,在我的示例中,如果在任何路径(右、左或下)中我获取该值并返回,直到它到达我的第一个函数调用。这样,true 值将一直传播到最后

希望我有帮助

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多