【发布时间】:2021-03-26 18:34:18
【问题描述】:
我正在尝试实现 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)的东西还是我误解了递归?
【问题讨论】:
-
你能解释一下为什么一个为 DFS 返回正确的结果而另一个没有?
-
@HarshaLimaye 当你从你的 for 循环中返回时,你会提前停止循环(当你退出函数返回给调用者时),在你的第二个例子中你没有返回,所以你您的循环在调用
dfs()后可以继续
标签: javascript algorithm recursion return depth-first-search