Topics / Data Structures & Algorithms / Q23
Find connected components in an undirected graph.
Short answer: Run DFS from each unvisited vertex. Every traversal marks exactly one connected component.
#include <stdbool.h>
#define N 8
static void mark(const bool g[N][N], int u, int id,
int component[N])
{
component[u] = id;
for (int v = 0; v < N; v++)
if (g[u][v] && component[v] == -1)
mark(g, v, id, component);
}
int components(const bool g[N][N], int component[N])
{
int count = 0;
for (int i = 0; i < N; i++) component[i] = -1;
for (int i = 0; i < N; i++)
if (component[i] == -1)
mark(g, i, count++, component);
return count;
}
Example: edges 0–1 and 2–3 form separate components; isolated vertices each form one component. The matrix must be symmetric. Time O(N²), space O(N). Directed graphs require a different algorithm for strongly connected components.