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.
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;
}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.
Checks 0/2