dfs function
DFS from start; calls visit(node, depth). maxDepth caps depth (-1 = no limit).
Recurses to the traversal depth; pass maxDepth to bound it for deep or
untrusted graphs, since deep recursion can exhaust the call stack.
Audited: 2026-06-12 11:26 EDT
Implementation
void dfs(
Adjacency graph,
int start,
void Function(int node, int depth) visit, {
int maxDepth = -1,
}) {
// Guard a bad/empty start before the recursion indexes `seen`.
if (start < 0 || start >= graph.length) return;
final List<bool> seen = List.filled(graph.length, false);
void go(int u, int d) {
if (seen[u]) return;
seen[u] = true;
visit(u, d);
if (maxDepth >= 0 && d >= maxDepth) return;
for (final int v in graph[u]) {
go(v, d + 1);
}
}
go(start, 0);
}