Graph Theory37 sections · 1633 units
Open in Course

Counting Components

Application 2

Problem: Count the number of connected components (Provinces). With DSU, this is direct.

Start with NN components (each node is its own component). Every time a union succeeds (returns true), you have merged two components into one. Decrement the count.

count := N
for each edge (u, v)
    if union(u, v) then
        count := count - 1
return count

The final count is your number of connected components. This pattern appears constantly: initialize count, decrement on successful unions. No need for extra traversals.