Example 1 — Reachability
Is there a route from 0 to another vertex?
#include <stdio.h>
#define V 6
static int adj[V][V], visited[V];
static void dfs(int u) {
visited[u] = 1;
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) dfs(v);
}
int main(void) {
int edges[][2] = {{0, 1}, {1, 2}, {3, 4}};
for (int i = 0; i < 3; i++) {
adj[edges[i][0]][edges[i][1]] = 1;
adj[edges[i][1]][edges[i][0]] = 1;
}
dfs(0);
printf("0 can reach 2: %s\n", visited[2] ? "yes" : "no");
printf("0 can reach 4: %s\n", visited[4] ? "yes" : "no");
return 0;
} How It Works
- DFS from 0 visits 0, 1, and 2.
- Vertices 3 and 4 form a separate island.
- Visited flags answer reachability.
