O (n) DFS. :
explore , , node. , DFS, node node .
, DFS node explore node. ( cc) explore , . , hashmap/dictionary , cc node. explore node cc . , , cc.
Each time it explorereturns to the DFS cycle, increment ccand pass this value the next time. After you finish with all of DFS, you will have a dictionary that maps to each node the corresponding number of the connected component. The value ccat the end of this procedure can give you the number of connected components that are on the graph.
Here's the pseudo code:
function explore(node, graph, cc, map){
map(currentNode) = cc
for i in stack:
explore(i, graph, cc, map)
}
function DFS{
int cc = -1
for node in keysOfGraph:
if not visited:
cc++
explore(node, graph, cc, map)
return cc
}
From Dasgupt Algorithms (section 3.2.3)
source
share