执行BFS/DFS算法时如何从遍历路径中找到最终路径
我正在尝试解决一个问题,该问题在树上应用广度优先搜索算法和深度优先搜索算法,并找出这两种算法找到的遍历路径和最终路径。
我实际上感到困惑的是如何计算这两条不同的路径?它们真的不同吗?
例如,考虑以下树,
假设我们的起始节点是 A,目标节点是 H 对于这两种
算法,这就是我认为的遍历路径和最终路径
- 对于 BFS
遍历路径: ABCDEFGH
最终路径: ACFH
如果这是它的工作原理,那么我怎样才能找到那条最终路径呢?找到走过的路径很容易,但找到最终路径就不那么容易了。
类似地,
- 对于 DFS
遍历路径: ABDECFG
最终路径: ACFH
再次,如何从 DFS 的遍历路径中提取最终路径。
这实际上变得有点复杂。如果我的目标节点可以从两侧到达怎么办?在这种情况下如何找到最终路径?
例如,考虑以下场景:
假设在本例中,我们的起始节点是 A,目标节点是 H。
使用 BFS 和 DFS 都很容易计算遍历路径。
但对于最终路径,“H”从两侧可达,从F可达,从G也可达
对于DFS,你可以将最终路径写为ACF G 因为从 F 节点开始,我们将首先到达 H(因为 G 仍未被探索,但是您仍然必须从遍历路径中提取此最终路径,我不知道该怎么做)
>但是对于BFS,你不能这样做。那么,在这种情况下我的最终路径是什么?在这种情况下应该有两条最终路径吗?
任何人都可以帮我解决这个问题吗?
I am trying to solve a problem which apples a Breadth-First Search Algorithm as well as Depth-First Search algorithm on a Tree and finds out the traversal and final paths that are found by both these algorithms.
What I am actually confused with is how do I calculate these two different paths? And are they really different?
For example, consider the following tree,
Let's say, that our starting node is A and Goal node is H
For both the algorithms, this is what I feel would be the Traversed and Final Paths
- For BFS
Traversal Path: A B C D E F G H
Final Path: A C F H
If this is how it works, then how can I find that Final Path? Its very easy to find traversed path, but not exactly so easy to find the Final Path.
Similarly,
- For DFS
Traversal Path: A B D E C F G
Final Path: A C F H
Again, how can I extract the Final Path from the Traversal Path for DFS.
This actually gets a bit more complicated. What if my Goal Node is reachable from two sides? How do I find the Final Path in such a scenario?
For example, Consider the following scenario,
Let's say for this case, our Starting Node is A and Goal Node is H, again.
Traversal path is very easy to compute with both BFS and DFS.
But for the Final Path, "H" is reachable from two sides, it is reachable from F and it is also reachable from G
For the DFS, you may write the final path as A C F G because from the F node, we would reach the H first (as G would still be unexplored, however you would still have to extract this Final Path from the Traversal path, which I do not know how to do)
But for BFS, you can not do that. So, what would be my Final Path in this scenario? Should there be two Final Paths in such a scenario?
Can anyone help me out in this please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[多种可能的]方法之一是维护目标到源节点的映射。每次前进时,记录哪个源节点进行了该前进。因此,在 BFS 情况下,它将如下所示:
然后,从最终节点开始,向后重建路径:
相同的方法适用于 DFS 和 Dijkstra
One [out of many possible] approach is to maintain a map of target to source node. Every time you advance, record which source node was made to make that advance. So, in BFS case it will look like:
Then, from the final node, reconstruct the path by going backward:
Same approach works for DFS and Dijkstra