data-structures · intermediate · ~15 min
Count components by repeated DFS.
For an undirected graph (symmetric adj):
int count_components(const int *adj,int n);
Return the number of connected components.
adj n×n symmetric 0/1.
Component count.
Each isolated vertex is its own component.
#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; }
Not resetting/sharing one visited array across the outer loop → overcounting.
No edges → n; connected → 1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.