← DFS / Recursion

Pattern Recognition Drill

#45 — Count connected components

Easy Graphs

The Problem

Count the number of connected components in an undirected graph.

What approach would you use?

Think about it before scrolling down.

Key Signals

DFS / Recursion

For each unvisited node, run DFS to mark its component. Count the number of DFS calls. O(V+E).

Alt: Queue / BFS

BFS works identically — just a different traversal strategy for the same counting approach.

Common Trap

Don't forget disconnected nodes — iterate over ALL nodes, not just starting from node 0.

← #44 #46 →