Shortest Path in Binary Matrix — LeetCode 1091 Python Solution

MediumBreadth-First SearchArrayMatrix
Problem
#1091
Reading time
3 min

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

Python
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 -1

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview