javascript - Variable not updating in recursive call
问题描述
I am trying to implement leetcode allpaths problem I have written the below solution, which is giving me the wrong output, I have purposefully, left the console statements for better debugging. Basically the variable path does not gets updated to [0] whenever the recursive call to findPath is done.
What am I missing here?
const allPaths = (edges) => {
const graph = buildAdjacencyListGraph(edges);
console.log(graph);
const result = []
let path = [0];
findPath(graph, 0, edges.length - 1, result, path)
}
const findPath = (graph, src, dest, result, path) => {
for (let neighbor of graph[src]) {
console.log('Path before push: ', path);
console.log('Result before push: ', result);
path.push(neighbor);
console.log('Path: ', path);
console.log('Result: ', result);
console.log('Neighbor', neighbor);
console.log('Destination: ', dest);
console.log('Is neighbor and dest equal?: ', dest === neighbor);
if (neighbor === dest) {
result.push([...path])
console.log('Result after equal: ', result);
path = [0];
console.log('Path after equal: ', path);
continue;
}
findPath(graph, neighbor, dest, result, path);
}
}
const buildAdjacencyListGraph = (edges) => {
const graph = {};
for (let [i, edge] of edges.entries()) {
graph[i] = edge;
}
return graph;
}
const graph = [[4,3,1],[3,2,4],[3],[4],[]]
allPaths(graph)
解决方案
有几个问题:
allPaths
没有return
声明。它应该以return result
.result.push([...path])
用 重置路径是错误path = [0]
的。路径应该只返回到其先前的状态,以便可以从那里探索替代的延续。通过将其设置为[0]
,循环的下一次迭代可能会向该路径添加一个节点,该路径根本没有从 0 开始的连接。在进行递归调用之后,路径应该在进行下一次迭代之前返回到其先前的状态,因为我们不希望将当前邻居保留在那里,在其后添加下一个邻居。不,下一个邻居应该替换路径中的当前邻居。
不是真正的问题,但您创建的邻接列表确实是不必要的。你得到的已经是一个邻接列表,它是一个列表列表而不是列表的字典。但是由于键是 0..n-1,所以它确实以相同的方式使用。您可以跳过该转换。
因此,通过这些更正,代码变为:
const allPaths = (edges) => {
// no need for calling buildAdjacencyListGraph
const result = [];
findPath(edges, 0, edges.length - 1, result, []); // no need for path variable
return result;
}
const findPath = (graph, src, dest, result, path) => {
for (let neighbor of graph[src]) {
path.push(neighbor);
if (neighbor === dest) {
result.push([...path]);
} else {
findPath(graph, neighbor, dest, result, path);
}
path.pop(); // backtrack!
}
}
推荐阅读
- typescript - 量角器:将自定义定位器添加到全局命名空间
- javascript - 通过 Jimp(node.js 模块)合成图像时,它返回一个空白图像而不是合成图像
- python - 如何添加将小数转换为分数,然后将其添加到列表中?
- python - 在 AWS Glue 开发终端节点上对 PyCharm 中的远程调试问题进行故障排除
- suffix - 仅在某些项目上自定义后缀哈希
- ios - 设置 tableView 数据源导致应用程序崩溃
- python - 尝试在 python 脚本中安装 python 包
- python - 我是 Tkinter python 新手,在 Python 中使用 Tkinter 创建顶级窗口时遇到问题
- python-3.x - 使用 Python 计算 netcdf 文件的变量相关性并在地图上绘制
- javascript - .html 无法呈现 .js 反应外部文件