01 Matrix — LeetCode 542 Python Solution
MediumBreadth-First SearchArrayDynamic ProgrammingMatrix
- Problem
- #542
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two cells sharing a common edge is 1.
Example
- Input
- mat = [[0,0,0],[0,1,0],[0,0,0]]
- Output
- [[0,0,0],[0,1,0],[0,0,0]]
Python solution
Python
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
ans = [[-1] * n for _ in range(m)]
q = deque()
for i, row in enumerate(mat):
for j, x in enumerate(row):
if x == 0:
ans[i][j] = 0
q.append((i, j))
dirs = (-1, 0, 1, 0, -1)
while q:
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and ans[x][y] == -1:
ans[x][y] = ans[i][j] + 1
q.append((x, y))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 542. 01 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
LeetCode 329Longest Increasing Path in a MatrixHardLeetCode 773Sliding PuzzleHardLeetCode 1162As Far from Land as PossibleMediumLeetCode 2328Number of Increasing Paths in a GridHardLeetCode 2556Disconnect Path in a Binary Matrix by at Most One FlipMediumLeetCode 2617Minimum Number of Visited Cells in a GridHard
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 542. 01 Matrix?
- LeetCode 542. 01 Matrix is rated Medium on LeetCode.
- What is the time complexity of LeetCode 542. 01 Matrix?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 542. 01 Matrix?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 542. 01 Matrix cover?
- LeetCode 542. 01 Matrix is tagged Breadth-First Search, Array, Dynamic Programming and Matrix on LeetCode.