MediumNo. 1091
Shortest Path in Binary Matrix — LeetCode 1091 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Breadth-First Search, Array, Matrix
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [[0,1],[1,0]]
- Output
- 2
Python solution
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0]:
return -1
n = len(grid)
grid[0][0] = 1
q = deque([(0, 0)])
ans = 1
while q:
for _ in range(len(q)):
i, j = q.popleft()
if i == j == n - 1:
return ans
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
grid[x][y] = 1
q.append((x, y))
ans += 1
return -1Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1091. Shortest Path in Binary Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0864 | Shortest Path to Get All Keys | Hard |
| 0909 | Snakes and Ladders | Medium |
| 0994 | Rotting Oranges | Medium |
| 1210 | Minimum Moves to Reach Target with Rotations | Hard |
| 1293 | Shortest Path in a Grid with Obstacles Elimination | Hard |
| 1765 | Map of Highest Peak | Medium |
Frequently asked questions
- How hard is LeetCode 1091. Shortest Path in Binary Matrix?
LeetCode 1091. Shortest Path in Binary Matrix is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1091. Shortest Path in Binary Matrix?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 1091. Shortest Path in Binary Matrix?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 1091. Shortest Path in Binary Matrix cover?
LeetCode 1091. Shortest Path in Binary Matrix is tagged Breadth-First Search, Array and Matrix on LeetCode.