I have been going through Breadth First Traversal at this link
Breadth First Traversal
Now what if the graph structure is changed to this
The node 3 is now disconnected from the graph. When traversal program is now used, it does'nt display vertex 3. Is there a way where we can dispaly this vertex as well?
To my understanding, BFS would keep looking for unvisited nodes as long as they exist; however, if this is not done, BFS only visits nodes in the connected component of the initial vertex. This seems to be more a matter of definition than an actual programming problem; simply restart the BFS implementation on unvisited nodes as long as they exist - if visiting of all connected components is desired.
Many implementations of BFS/DFS assume implicitly that the graph is connected.
Yes there is. If after finishing BFS still there are some unvisited vertices, enqueue them into the queue.
If you have a list of all nodes, your graph search algorithm of choice (DFS/BFS) will discover the connected components one at a time.
You could do this in the following way.
For example, consider your example graph in which there are 4 nodes and edges between
0, 2
,2, 0
and1, 2
and node3
has no incoming or outgoing edges.You would have a list of nodes
{0, 1, 2, 3}
And to discover all connected components, you would do the following:
where
dfs
is implemented in the usual way. Here when you run the code on our list{0,1,2,3}
, the nodes{0,1,2}
will be visited by the firstdfs
call and0,1,2
will be marked visited. Then when we come across3
, since it is not visited, there will be anotherdfs
call.Hope you get the idea.