Skip to content

Commit 82cfd86

Browse files
committed
Runtime: 534 ms (Top 69.67%) | Memory: 19.20 MB (Top 71.26%)
1 parent 3050ede commit 82cfd86

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed
+20-15
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,30 @@
1-
from collections import deque
2-
from typing import List
1+
// Runtime: 534 ms (Top 69.67%) | Memory: 19.20 MB (Top 71.26%)
32

43
class Solution:
54
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
6-
# Initialize a queue and a 2D array to store the distances
5+
if not mat or not mat[0]:
6+
return []
7+
8+
m, n = len(mat), len(mat[0])
79
queue = deque()
8-
dist = [[float('inf') for _ in range(len(mat[0]))] for _ in range(len(mat))]
10+
MAX_VALUE = m * n
911

10-
# Add all the 0s in the matrix to the queue and set their distance to 0
11-
for i in range(len(mat)):
12-
for j in range(len(mat[0])):
12+
# Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.
13+
for i in range(m):
14+
for j in range(n):
1315
if mat[i][j] == 0:
1416
queue.append((i, j))
15-
dist[i][j] = 0
17+
else:
18+
mat[i][j] = MAX_VALUE
19+
20+
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
1621

17-
# Perform breadth-first search
1822
while queue:
19-
i, j = queue.popleft()
20-
for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
21-
if 0 <= x < len(mat) and 0 <= y < len(mat[0]) and dist[x][y] > dist[i][j] + 1:
22-
dist[x][y] = dist[i][j] + 1
23-
queue.append((x, y))
23+
row, col = queue.popleft()
24+
for dr, dc in directions:
25+
r, c = row + dr, col + dc
26+
if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:
27+
queue.append((r, c))
28+
mat[r][c] = mat[row][col] + 1
2429

25-
return dist
30+
return mat

0 commit comments

Comments
 (0)