Shortest Path in Binary Matrix - Problem
Find the Shortest Clear Path in a Binary Matrix!
You're given an
Path Rules:
• You can only move through cells containing
• 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
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
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
⚠ Quadratic Growth
Space Complexity
O(n²)
Queue can contain up to O(n²) cells in worst case, plus visited array
⚠ 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)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code