我正在尝试实现 DFS,但我不明白在自身内部调用函数(递归)和返回函数调用(也是递归?)之间的区别
代码段 1:返回函数调用(错误答案)
在这种情况下,代码没有正确回溯。
const graph = {
1: [2, 3],
2: [4, 5],
3: [1],
4: [2, 6],
5: [2, 6],
6: [4, 5]
}
let visited = [];
const dfs = (node) => {
if (visited.includes(node))
return;
console.log(node);
visited.push(node);
for (let i = 0; i < graph[node].length; i++) {
if (!visited.includes(graph[node][i]))
return dfs(graph[node][i])
}
}
dfs(1);
片段 2:仅调用函数(正确答案)
似乎工作正常
const graph = {
1: [2, 3],
2: [4, 5],
3: [1],
4: [2, 6],
5: [2, 6],
6: [4, 5]
}
let visited = [];
const dfs = (node) => {
if (visited.includes(node))
return;
console.log(node);
visited.push(node);
for (let i = 0; i < graph[node].length; i++) {
if (!visited.includes(graph[node][i]))
dfs(graph[node][i])
}
}
dfs(1);
两者有什么区别? (我以为他们会是一样的)
这是某种特定于语言 (JS) 的东西还是我误解了递归?
最佳答案
当您返回“函数调用”时,您实际上返回了被调用函数产生的值。当你简单地递归调用一个函数而不返回它时,你不会对返回值做任何事情。它们都是递归的情况,当不在循环中时它们的工作方式相似。
在这种情况下,由于您在 for 循环中使用函数的返回值,一旦 dfs(graph[node][i])
第一次运行,函数就会结束通过返回一个值来执行(或者只是完成执行,就像在这种情况下)并退出堆栈调用,for 循环结束,函数执行也停止。
关于javascript - 返回函数调用与仅在递归期间再次调用函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65317500/