mediumGraphBFSGraphs

Shortest Path in Binary Matrix

mediumTime: O(n^2)Space: O(n^2)

Signals to notice

shortest path in binary grid8-directional movementBFS from corner to corner

Brute force first

DFS trying all paths — doesn't find shortest path efficiently and revisits cells. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

BFS from (0,0) to (n-1,n-1) allowing 8-directional movement. Only traverse 0-cells. The BFS level count gives the shortest path length. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

BFS guarantees shortest path in an unweighted grid. 8-directional movement means each cell has up to 8 neighbors. The path length counts cells visited, including start and end. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Forgetting to check if start or end cell is blocked (value 1) — return -1 immediately if either is blocked. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Graphs Pattern