dfs function

void dfs(
  1. Adjacency graph,
  2. int start,
  3. void visit(
    1. int node,
    2. int depth
    ), {
  4. int maxDepth = -1,
})

DFS from start; calls visit(node, depth). maxDepth caps depth (-1 = no limit).

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);
}