Shortest Path in Binary Matrix
Problem Statement
You are given an n × n grid of 0s (open) and 1s (blocked). Find the shortest clear path from the top-left cell to the bottom-right cell.
A clear path uses only open cells. Each step can go to any of the eight neighbours of the current cell: the four straight ones and the four diagonal ones. Diagonal steps are allowed.
Return the number of cells on the shortest clear path, start and end included. Return -1 if there is no clear path. If the start or the end cell is blocked, there is no path.
grid, an n × n grid of 0 and 1.
The number of cells on the shortest clear path, or -1.
Step diagonally from (0,0) to (1,1). The path has 2 cells.
Go right to (0,1), then diagonally to (1,2), then down to (2,2). That is 4 cells.
The start cell is blocked, so there is no clear path.
- • 1 ≤ n ≤ 100
- • Each cell is 0 or 1.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
DFS over every simple clear path; keep the fewest cells that reach the end
BFS from the top-left cell with 8 directions; the first pop of the end cell is the answer
Walk every clear path from the top-left cell that never reuses a cell. When a path reaches the bottom-right cell, record its cell count. The answer is the smallest count. Every path is walked to its end, so the work grows exponentially with the grid.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.