suppose that we have a adjacency list that represents a disconnected graph

I have a function that uses recursion in order to implement the DFS but it doesn't work when the graph is disconnected..

what's the best way to implement dfs on a disconnected graph?

12-31-2010

tabstop

You need to do dfs on each component of the graph. So pick a vertex, do dfs and you'll find the entire connected component which that vertex is on. Once you're done, pick another vertex (and keep picking until you find an unvisited one), and do it again. Lather, rinse, and repeat.

01-01-2011

nik

Quote:

Originally Posted by tabstop

You need to do dfs on each component of the graph. So pick a vertex, do dfs and you'll find the entire connected component which that vertex is on. Once you're done, pick another vertex (and keep picking until you find an unvisited one), and do it again. Lather, rinse, and repeat.