data-structures · intermediate · ~15 min
Depth-first traversal with a visited set.
int dfs_reachable_count(const int *adj,int n,int src);
Return how many vertices are reachable from src, including src itself, following directed edges.
adj n×n directed; 0<=src<n.
Reachable vertex count (≥1).
Use a visited array to avoid infinite loops on cycles.
#include <stddef.h>
/* Number of nodes reachable from `start` (including start) via DFS in the directed adjacency matrix. */
int dfs_reachable_count(const int *adj,int n,int start){ (void)adj;(void)n;(void)start; return 0; }
Forgetting to mark visited before recursing → infinite loop on a cycle.
src with no out-edges → 1; fully connected → n.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.