Blueprints · Breadth-First Search

BFS: Shortest Path in a Grid, From Brute-Force DFS to Early-Exit BFS

One problem, three stages: make it work, make it fast, make it lean. Step through each stage in the visualizer, then run all three on a big input in the benchmark and watch the brute force overheat.

The real-world version

A warehouse robot has to reach a shelf on a floor plan where some aisles are blocked. It needs the fewest moves, and the floor plan can be hundreds of cells on each side.

The problem

Given a grid where . is open, # is a wall, S is the start and E is the exit, return the fewest moves (up, down, left, right) from S to E, or -1 if it can't be reached.

S.#...
..#.#.
.....#
.##...
...#.E   →  9

X-ray: watch it run

Benchmark: will the forge overheat?

Run all three stages on a large input in your browser and compare the work each one does.

In the interview

If the edges have different costs (traffic, slopes), BFS no longer gives the shortest path. Say so, and name Dijkstra as the next step. It's the follow-up question interviewers almost always ask.