F · Specialist · 16 min

BFS: Shortest Paths on Unweighted Graphs

A queue plus a visited array is the shortest-path algorithm when every edge has the same cost — including every grid 'up/down/left/right' problem.

Breadth-first search explores in layers: everything 1 edge from the source, then 2, then 3. If every edge has length 1, the first time you reach a node is a shortest path. That is the theorem. The code is a queue.

Grids are graphs. A cell is a node; a 4-direction step is an edge. 'Minimum moves to the exit' is BFS, not DFS, and not Dijkstra — Dijkstra is for weighted edges.

Grid BFS skeletonjs
const DIRS = [
  [1, 0],
  [-1, 0],
  [0, 1],
  [0, -1],
];

function bfs(grid, sr, sc) {
  const h = grid.length;
  const w = grid[0].length;
  const dist = Array.from({ length: h }, () => Array(w).fill(-1));
  const q = [[sr, sc]];
  dist[sr][sc] = 0;
  for (let head = 0; head < q.length; head++) {
    const [r, c] = q[head];
    for (const [dr, dc] of DIRS) {
      const nr = r + dr;
      const nc = c + dc;
      if (nr < 0 || nc < 0 || nr >= h || nc >= w) continue;
      if (grid[nr][nc] === 1) continue; // wall
      if (dist[nr][nc] !== -1) continue;
      dist[nr][nc] = dist[r][c] + 1;
      q.push([nr, nc]);
    }
  }
  return dist;
}

TRACE

A 3×3 open grid, source in the center. Watch the layers.

Layer 0

Queue: [(1,1)]. dist[1][1] = 0.

source

1 / 3

DFS (stack / recursion) is the wrong tool for unweighted shortest paths: it dives deep and can discover a node via a long detour first. DFS shines for connectivity, cycle detection, finishing times, and some DP on trees.

Flood fill is BFS or DFS used only for 'what is reachable?' — you do not need distances. The Flood Fill Lab game is that idea with the wavefront drawn.

CHECK

Shortest path in a maze with equal-cost steps. Which algorithm?

CHECK

Counting islands on a grid of land/water. After you find an unvisited land cell, what do you do?

Checks 0/2

Next lesson