LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

Why does DFS(G) loop over all vertices, and how does that give the connected components?

One call DFS(G, v) only reaches the vertices of v's connected component. The driver first labels everything UNEXPLORED, then starts a search from every vertex that is still UNEXPLORED, and each start explores exactly one new component. Counting the starts counts the components, and the discovery edges of all starts together form a spanning forest.

DFS(G):
  for each vertex u:  label u UNEXPLORED
  for each edge e:    label e UNEXPLORED
  for each vertex v:
    if v is UNEXPLORED:
      DFS(G, v)            // a new component starts here

Disconnected graphs are common. Take the roads of the United States alone: no road joins the islands of Hawaii to each other or to the mainland, and Alaska can be reached by road only through Canada. A single DFS from New York would never reach Honolulu; the loop starts a fresh search there.

A vertex that is still unexplored after some searches cannot be connected to any vertex visited so far, or one of those searches would have reached it. So each new start opens a component nobody has touched yet, and no component is explored twice.

What falls out of the loop:

  • Is G connected? Exactly when the loop starts only one search.
  • Which component is v in? Number the starts and label every vertex with the number of the search that reached it; afterwards "are u and w connected?" is a comparison of two numbers, $O(1)$.
  • Spanning forest: the discovery edges, one tree per component.

The labelling and the loop add only $O(n + m)$ work, so the whole computation stays $O(n + m)$.

Go deeper:

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026