Shortest Path in Binary Matrix
Master this topic with zero to advance depth.
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
Clear path found with 4 units length.
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
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.
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
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.