从给定节点开始有向图的 BFS 遍历

发布于 2024-08-27 09:55:25 字数 684 浏览 8 评论 0原文

我对图的基本广度优先搜索遍历的理解是:

BFS        
    Start from any node. 
    Add it to queue. 
    Add it to visited array.

    While queue is not empty:
        Remove head from queue; 
        Print node.

        add all unvisited direct subchilds to que; 
        mark them as visited  

但是,如果我们必须从给定节点遍历有向图,并且并非所有节点都可以从给定节点(直接或间接),我们如何使用 BFS 遍历这种情况的图?

您能否也在此图中解释一下:

a=> b => d => e => d  
a=> c => d

这里如果起始节点是 b ,我们永远不会打印 ac

我在算法中遗漏了什么吗?

我使用了 HashMap; adj = new HashMap(); 创建邻接表来存储图。

My understanding of basic breadth-first search traversal for a graph is:

BFS        
    Start from any node. 
    Add it to queue. 
    Add it to visited array.

    While queue is not empty:
        Remove head from queue; 
        Print node.

        add all unvisited direct subchilds to que; 
        mark them as visited  

However, if we have to traverse a directed graph from a given node and not all nodes are accessible from the given node (directly or indirectly), how do we use BFS for traversing the graph of this situation?

Can you please explain in this graph as well:

a=> b => d => e => d  
a=> c => d

Here if the starting node is b , we never print a and c.

Am I missing something in the algorithm?

I used HashMap<String, ArrayList> adj = new HashMap(); to create the adjacency list to store graph.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抹茶夏天i‖ 2024-09-03 09:55:25

但是,如果我们必须从给定节点遍历有向图,并且并非所有节点都可以从给定节点[直接或间接]访问,我们如何使用 BFS 来实现相同目的。

搜索算法遍历图。如果有无法遍历的边,因此无法到达节点,则搜索将根本找不到它们。

However, if we have to traverse a DIRECTED graph from a given node and not all nodes are accessible from the given node [directly or indirectly] how do we use BFS for the same.

A search algorithm traverses a graph. If you have edges that cannot be traversed and thus nodes that cannot be reached, the search will simply not find them.

笑梦风尘 2024-09-03 09:55:25

您的理解是正确的,除了“从任意节点开始”部分之外——BFS 遍历必须从根节点开始。因此,在您的示例中,您必须从节点 a 开始,否则,正如您所说,您将永远不会访问它。

You are correct in your understanding, except for the "Start from any node" part -- a BFS traversal must begin from the root node. So in your example, you would have to begin with node a, otherwise, as you have said, you will never visit it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文