Skip to lesson

Multi-source BFS

Multi-source BFS seeds the queue with all initial origins simultaneously to compute shortest distances in a single traversal.

The core concept of multi-source BFS

Multi-source BFS is one BFS that starts from several origins at once, so each node gets its distance to the nearest origin. Standard BFS starts from a single origin node, but many problems ask for minimum distances from multiple starting locations.

Java
Queue<Integer> q = new ArrayDeque<>();int[] dist = new int[n];Arrays.fill(dist, -1);                 // -1 = not visited yetfor (int h : hospitals) {              // every source starts at distance 0    dist[h] = 0;    q.offer(h);}while (!q.isEmpty()) {                 // then an ordinary BFS    int u = q.poll();    for (int v : adj.get(u)) {        if (dist[v] == -1) { dist[v] = dist[u] + 1; q.offer(v); }    }}

For instance, find the distance from each residential home to the nearest hospital.

A brute force approach runs a separate BFS from every hospital or house. If there are k facilities, this takes O(k * (V + E)) total time. On a large graph, this duplicates substantial work and causes slow runtimes.

Instead, push all starting locations into the FIFO queue at time 0. Initialise their distance to 0 and mark them all visited before looping. BFS radiates outwards in simultaneous waves across all origins in optimal O(V + E) time.

Find the bug

Spot the multi-source bug

Select the line that is wrong.

Every source must start in the queue at distance 0.

Round 1 of 2

Spreading Outage step-by-step trace

In the Spreading Outage problem, a grid contains empty cells, healthy servers, and failed servers. Every minute, failed servers contaminate adjacent healthy neighbours. We seek the minimum minutes until no healthy server remains.

Example 1 · Spreading Outage Simulation in Java

Main.javaJava
import java.util.*;
public class Main {    static int minutesToFail(int[][] grid) {        int rows = grid.length;        int cols = grid[0].length;        Queue<int[]> q = new LinkedList<>();        int healthy = 0;
        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                if (grid[r][c] == 2) {                    q.offer(new int[]{r, c});                } else if (grid[r][c] == 1) {                    healthy++;                }            }        }
        if (healthy == 0) return 0;        int minutes = 0;        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!q.isEmpty()) {            int size = q.size();            boolean failedAny = false;            for (int i = 0; i < size; i++) {                int[] curr = q.poll();                int r = curr[0];                int c = curr[1];
                for (int[] d : dirs) {                    int nr = r + d[0];                    int nc = c + d[1];                    if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {                        grid[nr][nc] = 2;                        healthy--;                        failedAny = true;                        q.offer(new int[]{nr, nc});                    }                }            }            if (failedAny) minutes++;        }
        return healthy == 0 ? minutes : -1;    }
    public static void main(String[] args) {        int[][] grid = {            {2, 1, 1},            {1, 1, 0},            {0, 1, 1}        };        System.out.println("Minutes to fail all servers: " + minutesToFail(grid));    }}
Output
Minutes to fail all servers: 4

What this code does

  • Initial failed servers are pushed to the queue at minute 0 while counting healthy servers.
  • Level by level processing spreads the failure to adjacent 1s and decrements healthy count.
  • Returns elapsed minutes if healthy reaches 0, otherwise returns -1 for unreachable servers.

Brute force simulates minute by minute, scanning the entire grid each round. Scanning an R by C grid repeatedly can take up to O((R * C)^2) time. This full-scan simulation does unnecessary repeated inspections on static cells. With multi-source BFS, enqueue all failed servers at minute 0. Track the count of healthy servers. Each level expands fail to healthy neighbours, decrementing the healthy count. When the queue empties, return the elapsed minutes if healthy servers reach 0, else return -1.

Distance to the nearest zero cell

Given a binary matrix, find the distance to the nearest 0 for each cell. Starting BFS searches from each 1 looking for a 0 wastes significant time. Many overlapping searches scan the same empty cells repeatedly in O((R * C)^2) time.

Example 2 · Brute force: scan every zero for every cell, O((m * n)^2)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int[][] mat = {            {0, 0, 0},            {0, 1, 0},            {1, 1, 1}        };        int m = mat.length;        int n = mat[0].length;        int[][] dist = new int[m][n];
        for (int r = 0; r < m; r++) {            for (int c = 0; c < n; c++) {                int best = Integer.MAX_VALUE;                for (int zr = 0; zr < m; zr++) {            // check every zero for this cell                    for (int zc = 0; zc < n; zc++) {                        if (mat[zr][zc] == 0) {                            best = Math.min(best, Math.abs(r - zr) + Math.abs(c - zc));                        }                    }                }                dist[r][c] = best;            }        }        for (int[] row : dist) System.out.println(Arrays.toString(row));    }}
Output
[0, 0, 0]
[0, 1, 0]
[1, 2, 1]

What this code does

  • Every cell compares itself with every zero, using row distance plus column distance.
  • That is m * n cells times m * n zeros in the worst case, so O((m * n)^2).
  • It matches BFS here because the grid has no walls; multi-source BFS also handles walls and runs in O(m * n).

Example 3 · Optimal: multi-source BFS, O(m * n) time and space

Main.javaJava
import java.util.*;
public class Main {    static int[][] updateMatrix(int[][] mat) {        int m = mat.length;        int n = mat[0].length;        int[][] dist = new int[m][n];        for (int[] row : dist) Arrays.fill(row, -1);
        Queue<int[]> q = new LinkedList<>();        for (int r = 0; r < m; r++) {            for (int c = 0; c < n; c++) {                if (mat[r][c] == 0) {                    dist[r][c] = 0;                    q.offer(new int[]{r, c});                }            }        }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};        while (!q.isEmpty()) {            int[] curr = q.poll();            int r = curr[0];            int c = curr[1];
            for (int[] d : dirs) {                int nr = r + d[0];                int nc = c + d[1];                if (nr >= 0 && nr < m && nc >= 0 && nc < n && dist[nr][nc] == -1) {                    dist[nr][nc] = dist[r][c] + 1;                    q.offer(new int[]{nr, nc});                }            }        }
        return dist;    }
    public static void main(String[] args) {        int[][] mat = {            {0, 0, 0},            {0, 1, 0},            {1, 1, 1}        };        int[][] res = updateMatrix(mat);        for (int[] row : res) {            System.out.println(Arrays.toString(row));        }    }}
Output
[0, 0, 0]
[0, 1, 0]
[1, 2, 1]

What this code does

  • All zero cells are enqueued first with distance 0.
  • Unvisited cells with -1 receive current distance plus 1 on discovery.
  • Guarantees optimal shortest distance from any 1 to the closest 0 in O(M * N) time.
  • All zeros start in the queue together, so every cell is reached once, instead of being compared with every zero.

Example 4 · Walls and Gates Nearest Distance in Java

Main.javaJava
import java.util.*;
public class Main {    static final int INF = 2147483647;
    static void wallsAndGates(int[][] rooms) {        int m = rooms.length;        int n = rooms[0].length;        Queue<int[]> q = new LinkedList<>();
        for (int r = 0; r < m; r++) {            for (int c = 0; c < n; c++) {                if (rooms[r][c] == 0) {                    q.offer(new int[]{r, c});                }            }        }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};        while (!q.isEmpty()) {            int[] curr = q.poll();            int r = curr[0];            int c = curr[1];
            for (int[] d : dirs) {                int nr = r + d[0];                int nc = c + d[1];                if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] == INF) {                    rooms[nr][nc] = rooms[r][c] + 1;                    q.offer(new int[]{nr, nc});                }            }        }    }
    public static void main(String[] args) {        int[][] rooms = {            {INF, -1, 0, INF},            {INF, INF, INF, -1},            {INF, -1, INF, -1},            {0, -1, INF, INF}        };        wallsAndGates(rooms);        System.out.println("Row 0: " + Arrays.toString(rooms[0]));        System.out.println("Row 1: " + Arrays.toString(rooms[1]));    }}
Output
Row 0: [3, -1, 0, 1]
Row 1: [2, 2, 1, -1]

What this code does

  • Gates holding value 0 are added to the queue at start.
  • Unvisited empty rooms marked INF get distance incremented from the current gate.
  • Walls marked -1 are never overwritten or traversed.

Reverse the search direction by starting from all zeroes simultaneously. Add every cell containing 0 to the queue with distance 0. Initialise an answer matrix with -1 for all ones. Pop cells from the queue and inspect four directional neighbours. When an unvisited cell with -1 is encountered, set its distance to current distance plus 1. Enqueue that neighbour and continue until every cell is resolved in O(R * C) time.

Next step

Check your understanding

10 quick questions