580 views
1 votes
1 votes
Does BFS and DFS traversal sequence exist for disconnected graphs? Is yes can you please give a dry run of the algorithm on a disconnected graph?

According to me it should not exist as there is no edge to visit certain vertices of a different graph component from the source vertex in a disconnected graph. There is no absolute answer I could find online to this question.

1 Answer

Best answer
1 votes
1 votes

Does BFS and DFS traversal sequence exist for disconnected graphs? Is yes can you please give a dry run of the algorithm on a disconnected graph?

Yes.

We start BFS or DFS on any random vertex (s) . Now BFS or DFS will print all the vertices which are reachable from s. 

What about other vertices? The graph can be disconnected.

To handle this situation we can do a little bit of modification in our algorithm. We will use an array of size V(number of vertices). Whenever we will visit a vertex we will mark it as visited.

Our code will be like this:

For all the vertices v of G

{

    if(visited[v] == false)

     BFS(v) or DFS(v) // count++;

}

the count will give us the number of connected components.

selected by

Related questions

1 votes
1 votes
1 answer
1
Sandy Sharma asked Apr 24, 2018
799 views
Is this statement correct?? and why?.If there are negative weight cycles than dijkstra will surely fail but if there are negative weight edges(need not be cycle) then dij...