AlgoFrames

0-1 BFS and multi-source BFS

When edge weights are only 0 or 1, a deque replaces the priority queue. Multi-source BFS starts from many sources at once, as in rotting oranges.

Before you start: Bellman-Ford and negative edges.

The idea

Walk from S to T through a grid. You may remove obstacles, and you want to remove as few as possible.

Stepping onto an open cell costs 0 and onto an obstacle costs 1. The answer is a shortest path with weights 0 and 1.

Intuition

Each step costs 0 or 1. Plain BFS counts steps, so it would treat both moves the same.

Dijkstra handles these weights, but its heap costs O(log V) per operation. With only two weights a deque is enough.

Put a 0-cost neighbor at the front and a 1-cost neighbor at the back. The deque then stays sorted by cost.

Every entry costs d or d + 1, where d is the cost at the front. Front pushes add d, back pushes add d + 1.

Complexity

Each cell is finished once and each move is checked once. Deque pushes and pops cost O(1), so the total is O(V + E).

Dijkstra on the same grid pays O(log V) per heap operation, so it needs O((V + E) log V).

Pitfalls

A cell can enter the deque twice, first at the back and later cheaper at the front. Skip the old copy when it is popped.

With many sources, queue all of them at the start. One BFS per source repeats the work for every source.

A single queue that starts with every source gives each cell its distance to the nearest source in one pass.

Variations

A weight of 5 breaks the two-cost rule of the deque. For general weights, use Dijkstra instead.

Code

Pseudocode

dist[all] ← ∞, dist[start] ← 0
deque ← [(0, start)]
while deque not empty
  (d, cell) ← pop the front of deque
  if d > dist[cell]: continue
  if cell is the goal: return d
  for each neighbor next of cell
    w ← cost to enter next (0 or 1)
    if d + w < dist[next]
      dist[next] ← d + w
      if w = 0: push (d, next) to the front
      else: push (d + 1, next) to the back
return dist

Python

from collections import deque
def min_obstacles(grid):
    rows, cols = len(grid), len(grid[0])
    dist = [[float("inf")] * cols for _ in range(rows)]
    dist[0][0] = 0
    dq = deque([(0, 0, 0)])
    while dq:
        d, r, c = dq.popleft()
        if d > dist[r][c]:
            continue
        if (r, c) == (rows - 1, cols - 1):
            return d
        for nr, nc in ((r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                w = grid[nr][nc]
                if d + w < dist[nr][nc]:
                    dist[nr][nc] = d + w
                    if w == 0:
                        dq.appendleft((d, nr, nc))
                    else:
                        dq.append((d + 1, nr, nc))
    return -1

JavaScript

function minObstacles(grid) {
  const rows = grid.length, cols = grid[0].length;
  const dist = grid.map((row) => row.map(() => Infinity));
  dist[0][0] = 0;
  const dq = [[0, 0, 0]];
  while (dq.length > 0) {
    const [d, r, c] = dq.shift();
    if (d > dist[r][c]) continue;
    if (r === rows - 1 && c === cols - 1) return d;
    for (const [nr, nc] of [[r - 1, c], [r, c + 1], [r + 1, c], [r, c - 1]]) {
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
      const w = grid[nr][nc];
      if (d + w < dist[nr][nc]) {
        dist[nr][nc] = d + w;
        if (w === 0) dq.unshift([d, nr, nc]);
        else dq.push([d + 1, nr, nc]);
      }
    }
  }
  return -1;
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputWeights 0 or 1; one or many sources
OutputShortest distances

Practice problems (5)

Front or back of the deque Warm-up

Follow 0-1 BFS from the top-left cell. Stepping onto a 0 cell costs 0 and onto a 1 cell costs 1. After each pop, type the cost that the next relaxed cell gets.

Which structure for 0 and 1 weights? Warm-up

Every edge of a graph weighs 0 or 1. You need shortest distances from one source in O(V + E). Which structure holds the cells waiting to be processed?

Rotting oranges Standard

Each cell of grid is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, each fresh orange next to a rotten one (up, down, left or right) becomes rotten.

Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

Minimum obstacle removal Standard

Each cell of grid is 0 (empty) or 1 (obstacle). You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left or right. You may remove obstacles.

Return the fewest obstacles you must remove.

Distance to the nearest 0 Standard

Each cell of mat is 0 or 1. For every cell, find how many steps (up, down, left or right) it takes to reach the nearest 0.

Return a matrix of the same size with those distances.

Related topics

Next on the path: Floyd-Warshall: all pairs