Shortest Path in Binary Matrix
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Graphs.
Shortest Path in Binary Matrix
Given an
n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.A clear path in a binary matrix is a path from the top-left cell (i.e.,
(0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:- All the visited cells of the path are
0. - All the adjacent cells of the path are 8-directionally connected.
- The length of a clear path is the number of visited cells of this path.
Visual Representation
Grid:
0 0 0
1 1 0
1 1 0
Path: (0,0) -> (0,1) -> (1,2) -> (2,2)
Length: 4Examples
Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Clear path found with 4 units length.
Approach 1
Level II: Intermediate (BFS without In-place Modification)
Intuition
A standard BFS using a
visited set instead of modifying the input grid. This is often preferred in production code to avoid side effects.Thought Process
- Check starting and ending cells.
- Use a
visitedset to store(r, c). - Queue stores
(r, c, distance). - Standard 8-directional exploration.
Pattern: BFS with Visited Set
⏱ O(N^2) - Same as optimal but with higher constant factor due to hashing.💾 O(N^2) - For the visited set.
Detailed Dry Run
3x3 grid, (0,0) is clear.
- Queue: [(0,0,1)], Visited: {(0,0)}
- Pop (0,0,1). Neighbors: (0,1), (1,1), (1,0). Add all to Visited and Queue.
- Continue until (n-1, n-1) is reached.
Approach 2
Level III: Optimal (BFS with In-place Marking)
Intuition
To optimize space and constant time, we can mark visited cells directly in the
grid (e.g., set grid[r][c] = 1). BFS finds the shortest path in an unweighted grid.Thought Process
- Early exits for blocked start/end.
- Queue for BFS starting at
(0, 0, 1). - Mark
grid[0][0] = 1. - Explore all 8 neighbors using a predefined
directionsarray. - If neighbor is
0, mark as1and queue it.
Pattern: 8-Direction BFS
⏱ O(N^2) - Every cell visited once.💾 O(N^2) - Worst case queue size (perimeter of search).
Detailed Dry Run
2x2 grid [[0,1],[1,0]]
- (0,0) Start. Mark grid[0][0]=1.
- Neighbors: (0,1)-X, (1,0)-X, (1,1)-OK.
- (1,1) reached. Return 2.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.