Graphs · Pattern 6 of 14

Multi-source BFS: spread from many starts at once

Put every starting cell in the queue before the first step. The BFS then spreads from all of them together, and each cell is reached first by its nearest source.

4 variations · 8 problems · 3 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

  • Something spreads from several places at the same time (rot, fire, water)
  • The distance from each cell to its nearest source
  • Searching from every source one by one would be too slow

The template

Multi source BFS
int orangesRotting(int[][] grid) {
    int m = grid.length, n = grid[0].length, fresh = 0;
    Deque<int[]> q = new ArrayDeque<>();
    for (int r = 0; r < m; r++)
        for (int c = 0; c < n; c++) {
            if (grid[r][c] == 2) q.offer(new int[]{r, c});   // every source starts in the queue
            else if (grid[r][c] == 1) fresh++;
        }
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    int minutes = 0;
    while (!q.isEmpty() && fresh > 0) {
        for (int size = q.size(); size > 0; size--) {          // one minute
            int[] cur = q.poll();
            for (int[] d : dirs) {
                int r = cur[0] + d[0], c = cur[1] + d[1];
                if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 1) {
                    grid[r][c] = 2; fresh--;
                    q.offer(new int[]{r, c});
                }
            }
        }
        minutes++;
    }
    return fresh == 0 ? minutes : -1;
}

The variations

  1. 1Spread from every source at once

    Queue all rotten oranges, gates or fires first, then BFS level by level: each level is one minute. To escape a fire, first record when the fire reaches each cell, then check that you get there strictly sooner.

  2. 2Distance to the nearest source

    Start from every 0, every thief or one whole island, and the first time BFS reaches a cell is its distance to the nearest one. For the safest path, compute those distances first, then find the path that keeps the smallest one as large as possible.

  3. 3Search backwards from the goal

    Instead of asking where water from each cell can go, start from each ocean and climb uphill. The cells reached from both oceans are the answer: two searches instead of one per cell.

  4. 4One BFS per source, then combine

    When you need the total distance to every source (every building), run a BFS from each one and add its distances into a shared grid, with a count of how many reached each cell. Only cells reached by all of them count.

Mistakes to avoid

  • Counting a minute for the last level even though it rotted nothing: stop once nothing is fresh, or the answer is one too big.
  • Running a separate BFS from every source: that is O(k·m·n). One queue with all sources is O(m·n).
  • Forgetting the case with no fresh oranges at all: the answer is 0, not −1.
Next: Cycle detection and bipartite graphs →

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