← Back to problems
UNSW COMP2521 · medium

DFS: Count Connected Components

DFS: count the connected components

Read an undirected graph and print how many connected components it has (a group of mutually reachable vertices is one component; an isolated vertex is its own component). This is a classic DFS use.

dfs is provided (it marks a whole component from a start vertex). Complete countComponents: scan every vertex, and whenever you find one not yet visited, launch a new dfs and add 1 to the count.

Pitfall (straight from the bug lab): the graph may be disconnected, so a single DFS from vertex 0 misses the other parts. You must for (v = 0..V-1) if (!visited[v]) { dfs(v); count++; } — each fresh DFS launch discovers one new component.

Input

  • Line 1: V E.
  • Next E lines: u v, an undirected edge (E may be 0).

Output

  • One line: the number of connected components.

Example: input 5 2 / 0 1 / 2 3 -> 3 (the components {0,1}, {2,3}, {4}).