Shortest Path in Binary Matrix
On this page
Problem statement
Given an n × n grid of 0s (open) and 1s (blocked), return the number of cells on the shortest path from the top-left cell to the bottom-right cell, moving through open cells only. From a cell you may step to any of its 8 neighbours (including diagonals). If either corner is blocked or no path exists, return −1.
The classic "shortest path in a grid" question: every move costs the same, so BFS is the whole answer, and the interview is about getting the details right (directions, start cell, visited marking). Original problem: LeetCode 1091.
Example

grid = [[0, 0, 0, 1],
[1, 1, 0, 1],
[1, 1, 0, 0],
[1, 1, 1, 0]]
Output: 5 # (0,0) (0,1) (1,2) (2,3) (3,3)
grid = [[1, 0],
[0, 0]]
Output: -1 # the start cell is blocked
Constraints (assumed)
- 1 ≤ n ≤ 100; each cell is 0 or 1.
What this question tests
- Seeing the grid as a graph with unit-cost edges, so BFS gives shortest paths.
- Exact details: 8 directions, bounds checks, visited when enqueued, blocked corners.
- Knowing what changes for weighted cells (Dijkstra) or guided search (A*).
Questions to ask first
- Which moves are allowed? (Here: 8 directions. Many grid problems use 4.)
- Do we count cells or steps? (Here: cells, so a 1 × 1 open grid returns 1.)
- Can I modify the grid to mark visited cells? If not, use a separate set.
- Is the grid always square? (Here: yes; the code works for rectangles with small changes.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.