views:

375

answers:

2

Hi,

My understanding of basic BFS traversal for a graph is:

BFS

{

Start from any node . Add it to que. Add it to visited array

While(que 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 the same.

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.

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

Any pointers are greatly appreciated.

Thanks.

+1  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.

RarrRarrRarr
The same goes for depth-first search, too.
Thilo
Graphs don't necessarily have root nodes. The question is clearly about graphs.
Ross
However, the question, from what I can see, is about DAGs and DAGs do have one or more root nodes (and if it has more than one root node, any graph-search algorithm will miss some nodes, unless all root nodes are added to the initial set).
Vatine
Thanks for your comments .I am sure this issue would be faced in number of real problems.Is there any algorithm to find a root node in DAGs. I want to traverse the complete graph from a root, similar to "testing bipartiteness" problem.Thanks
+1  A: 

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.

Thilo