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.