Graphs · Pattern 4 of 14

BFS for the shortest path

When every move costs 1, BFS reaches each node first along a shortest path. Count the levels until you pop the target. The node can be a cell, a word, a whole board or a cell plus extra state.

5 variations · 12 problems · 1 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

  • Minimum number of moves, steps or transformations
  • Every move has the same cost
  • The "node" is a state you can build: a string, a board, a position plus keys

The template

BFS for shortest path
int shortestPathBinaryMatrix(int[][] grid) {
    int n = grid.length;
    if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
    Deque<int[]> q = new ArrayDeque<>();
    q.offer(new int[]{0, 0});
    grid[0][0] = 1;                                   // mark visited when you push
    for (int dist = 1; !q.isEmpty(); dist++) {
        for (int size = q.size(); size > 0; size--) {   // everything at this distance
            int[] cur = q.poll();
            if (cur[0] == n - 1 && cur[1] == n - 1) return dist;
            for (int dr = -1; dr <= 1; dr++)
                for (int dc = -1; dc <= 1; dc++) {     // 8 directions
                    int r = cur[0] + dr, c = cur[1] + dc;
                    if (r >= 0 && c >= 0 && r < n && c < n && grid[r][c] == 0) {
                        grid[r][c] = 1;
                        q.offer(new int[]{r, c});
                    }
                }
        }
    }
    return -1;
}

// state BFS: the nodes are strings, and the neighbours are built on the fly
int openLock(String[] deadends, String target) {
    Set<String> seen = new HashSet<>(Arrays.asList(deadends));
    if (!seen.add("0000")) return -1;                 // the start itself is dead
    Deque<String> q = new ArrayDeque<>(List.of("0000"));
    for (int steps = 0; !q.isEmpty(); steps++) {
        for (int size = q.size(); size > 0; size--) {
            String s = q.poll();
            if (s.equals(target)) return steps;
            char[] c = s.toCharArray();
            for (int i = 0; i < 4; i++) {
                char orig = c[i];
                for (int d : new int[]{1, 9}) {      // turn wheel i up or down
                    c[i] = (char) ('0' + (orig - '0' + d) % 10);
                    String next = new String(c);
                    if (seen.add(next)) q.offer(next);
                }
                c[i] = orig;
            }
        }
    }
    return -1;
}

The variations

  1. 1Shortest path on a grid or board

    Cells are nodes and allowed moves are edges: 8 directions, knight jumps, or a die roll plus a snake or ladder. Count BFS levels until you pop the target.

  2. 2Strings as nodes

    Each word or lock code is a node; change one letter or one wheel to get a neighbour, and keep only the ones in the dictionary and not yet seen. For all shortest ladders, record each word's parents level by level, then backtrack from the end.

    Worked example Word Ladder Hard Read the solution
  3. 3The whole board is the state

    Encode the board as a string or a bitmask (a 2 × 3 puzzle, a small 0/1 matrix, a row of balls plus a hand). Every legal move gives a neighbouring state. The state space is small, so plain BFS finds the fewest moves.

  4. 4Position plus extra state

    The node is (row, col, something): obstacles you may still remove, or a bitmask of keys collected. Two visits to the same cell with different extras are different nodes.

  5. 5BFS over groups

    When one step lets you reach a whole group (every stop on a bus route), make the groups the nodes. Map each stop to its routes, and mark a route as used the first time you board it so you never scan it again.

    Worked example Bus Routes Hard Read the solution

Mistakes to avoid

  • Marking visited on pop: on a grid the same cell gets queued from several neighbours and the queue blows up.
  • Visiting a position only once when the state has more to it (obstacles left, keys held). The visited set must hold the whole state, not only the cell.
  • Word ladder: comparing every pair of words is O(n²·L). Generate neighbours by changing each letter to a–z and looking them up in a set instead.
Next: The complement trick: search from the border →

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