【发布时间】: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标志着沿路径的有效“步骤”?而不是 all1s 的图表,也许您应该显示一些其他输入及其预期输出?
标签: javascript recursion