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.
Implementation
void dfs(
Adjacency graph,
int start,
void Function(int node, int depth) visit, {
int maxDepth = -1,
}) {
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);
}