data-structures · intermediate · ~15 min

Count connected components

Count components by repeated DFS.

Challenge

For an undirected graph (symmetric adj):

int count_components(const int *adj,int n);

Return the number of connected components.

Input format

adj n×n symmetric 0/1.

Output format

Component count.

Constraints

Each isolated vertex is its own component.

Starter code

#include <stddef.h>
/* Number of connected components in an UNDIRECTED graph (adjacency matrix is symmetric). */
int count_components(const int *adj,int n){ (void)adj;(void)n; return 0; }

Common mistakes

Not resetting/sharing one visited array across the outer loop → overcounting.

Edge cases to handle

No edges → n; connected → 1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.