mediumGraphBFSGraphs

Shortest Path in Binary Matrix

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

Recognize the pattern

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

Brute force idea

If you approach Shortest Path in Binary Matrix in the most literal way possible, you get this: 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.

Better approach

The real unlock in Shortest Path in Binary Matrix comes when you notice this: 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.

Key invariant

The compass for Shortest Path in Binary Matrix is this: 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.

Watch out for

A common way to get lost in Shortest Path in Binary Matrix is this: 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