从深度搜索的路径中删除带有死胡同的节点
如果我委托console.log访问了节点,我会得到很多我不想要的备用节点。
我正是开始结束节点所需的节点(不需要最短),但是我不希望算法在找到正确的路径之前所采取的所有其他路径/节点
function dfs(start, visited = new Set()) {
console.log(start)
visited.add(start);
const destinations = adjacencyList.get(start);
for (const destination of destinations) {
if (destination === 'BKK') {
console.log(`DFS found Bangkok`)
return;
}
if (!visited.has(destination)) {
dfs(destination, visited);
}
}
}
dfs('PHX')
If I console.log visited nodes, I get a ton of spare nodes that I don't want.
I just what the nodes necessary to get for start to end node (does not need to be the shortest), But I don't want all the other paths/nodes the algo took before it found the right path
function dfs(start, visited = new Set()) {
console.log(start)
visited.add(start);
const destinations = adjacencyList.get(start);
for (const destination of destinations) {
if (destination === 'BKK') {
console.log(`DFS found Bangkok`)
return;
}
if (!visited.has(destination)) {
dfs(destination, visited);
}
}
}
dfs('PHX')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的想法是跟踪您访问的节点
目标>目标
导致纠正路径。因此,您应该在耗尽特定节点后返回,是否可以通过此节点访问end节点。请注意,这将从开始 - >从结束到开始时以相反的顺序结束。
要从
开始..-> .. finish
的路径,您可以存储在某些数组(而不是Console.log)中,并在DFS完成后逆转。The idea here is to track if the node
destination
you visited leads to correct path or not. Hence, you should return after exhausting a particular node whether end node can be visited through this node or not.Notice that this will print nodes from start -> finish in reverse order i.e. from finish to start.
To have path from
start ..->..finish
, you can store in some array(instead of console.log) and reverse that after dfs is complete.