我对图的基本广度优先搜索遍历的理解是:
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
, 我们从不打印 a
和 c
.
我是否遗漏了算法中的某些内容?
我用了HashMap<String, ArrayList> adj = new HashMap();
创建邻接表来存储图。
最佳答案
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.
搜索算法遍历图。如果您有无法遍历的边,因此无法到达节点,搜索将根本找不到它们。
关于algorithm - 从给定节点对有向图进行 BFS 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582576/