Graphs · Pattern 1 of 14

BFS and DFS: walking a graph

Build an adjacency list, then visit every reachable node once. BFS uses a queue and goes out level by level; DFS goes deep first with recursion or a stack.

5 variations · 9 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Visit, copy or collect every node you can reach
  • A hierarchy (manager and employees) given as lists of ids
  • Neighbours you only discover while you walk (links on a page, keys in boxes)
  • An edge or node whose removal disconnects the graph

The template

BFS / DFS Basics
List<List<Integer>> build(int n, int[][] edges) {   // undirected adjacency list
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
    return adj;
}

// BFS level by level: dist[v] = fewest edges from src (-1 if unreachable)
int[] bfsDist(int n, int[][] edges, int src) {
    List<List<Integer>> adj = build(n, edges);
    int[] dist = new int[n];
    Arrays.fill(dist, -1);
    Deque<Integer> q = new ArrayDeque<>();
    q.offer(src); dist[src] = 0;                    // mark when you push, not when you pop
    for (int level = 1; !q.isEmpty(); level++) {
        for (int size = q.size(); size > 0; size--) {   // one whole level
            int u = q.poll();
            for (int v : adj.get(u)) if (dist[v] == -1) { dist[v] = level; q.offer(v); }
        }
    }
    return dist;
}

// DFS: go deep first; returns the nodes in the order they are first visited
int[] dfsOrder(int n, int[][] edges, int src) {
    List<Integer> order = new ArrayList<>();
    dfs(src, build(n, edges), new boolean[n], order);
    return order.stream().mapToInt(Integer::intValue).toArray();
}
void dfs(int u, List<List<Integer>> adj, boolean[] seen, List<Integer> order) {
    seen[u] = true;
    order.add(u);
    for (int v : adj.get(u)) if (!seen[v]) dfs(v, adj, seen, order);
}

The variations

  1. 1Copy or collect while you walk

    Do a normal BFS or DFS and build something on the way: a clone of every node (a map from old node to new one is also the visited set), or the current path, added to the answer when you reach the target.

    Worked example Clone Graph Medium Read the solution
  2. 2A hierarchy as a tree

    Turn "manager of each employee" into a list of children per manager, then DFS from the head. Add up values on the way down (importance), or pass the time so far and keep the largest (time to inform everyone).

    Now you solve
  3. 3Neighbours you discover as you go

    The graph is not given up front. Each node you visit reveals its neighbours: the links on a page, or the boxes and keys inside a box. BFS with a visited set still works; just generate the edges when you pop a node.

    Worked example Web Crawler Medium Read the solution
  4. 4Bridges: DFS with low-link values

    Number the nodes in DFS order (disc). low[u] is the smallest number reachable from u's subtree using one back edge. An edge u–v is a bridge when low[v] > disc[u]: nothing below v can climb back above it.

  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Forgetting the visited set when cloning or crawling: a cycle sends you round forever. A map from original to copy doubles as the visited set.
  • Using a visited set in "all paths from source to target": the graph is a DAG and you want every path, so backtrack instead of marking nodes for good.
  • In bridge finding, comparing low[v] with the parent through the edge you came in on. Skip that one edge, or every edge looks like it sits on a loop.
Next: Grids as graphs: flood fill and islands →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.