Shortest Path in Binary Matrix - Problem
Find the Shortest Clear Path in a Binary Matrix!

You're given an n × n binary matrix where 0 represents an open cell and 1 represents a blocked cell. Your mission is to find the shortest clear path from the top-left corner (0, 0) to the bottom-right corner (n-1, n-1).

Path Rules:
• You can only move through cells containing 0
• You can move in 8 directions (horizontally, vertically, and diagonally)
• The path length is the number of cells visited (including start and end)

If no clear path exists, return -1. Think of it like navigating through a maze where you want to find the quickest route while avoiding obstacles!

Input & Output

example_1.py — Basic Path
$ Input: grid = [[0,0,0],[1,1,0],[0,0,0]]
Output: 4
💡 Note: The shortest clear path is (0,0) → (0,1) → (0,2) → (1,2) → (2,2) with length 4. We can move diagonally and around obstacles.
example_2.py — No Path
$ Input: grid = [[0,1],[1,0]]
Output: -1
💡 Note: There's no clear path from top-left to bottom-right because the path is completely blocked by obstacles.
example_3.py — Single Cell
$ Input: grid = [[0]]
Output: 1
💡 Note: The grid has only one cell (0,0) which is both start and destination, so the path length is 1.

Visualization

Tap to expand
BFS Wave-like Expansion Pattern12X6Distance 1 (Start)Distance 2Distance 3Distance 4+Blocked CellTarget Found!Shortest Path Length = 6
Understanding the Visualization
1
Initialize Queue
Start with source cell (0,0) in the queue with distance 1
2
Level-by-Level Expansion
Process all cells at current distance before moving to next distance
3
8-Direction Exploration
From each cell, explore all 8 possible directions (including diagonals)
4
Early Termination
Return immediately when destination is reached - guaranteed shortest!
Key Takeaway
🎯 Key Insight: BFS guarantees the shortest path because it explores all nodes at distance k before any nodes at distance k+1, making it perfect for unweighted shortest path problems!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

In worst case, we visit every cell in the n×n grid exactly once

n
2n
Quadratic Growth
Space Complexity
O(n²)

Queue can contain up to O(n²) cells in worst case, plus visited array

n
2n
Quadratic Space

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 ≤ n ≤ 100
  • grid[i][j] is 0 or 1
  • You can move in 8 directions (including diagonals)
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
67.2K Views
High Frequency
~25 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen