|
1 |
| -from collections import deque |
2 |
| -from typing import List |
| 1 | +// Runtime: 534 ms (Top 69.67%) | Memory: 19.20 MB (Top 71.26%) |
3 | 2 |
|
4 | 3 | class Solution:
|
5 | 4 | 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]) |
7 | 9 | queue = deque()
|
8 |
| - dist = [[float('inf') for _ in range(len(mat[0]))] for _ in range(len(mat))] |
| 10 | + MAX_VALUE = m * n |
9 | 11 |
|
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): |
13 | 15 | if mat[i][j] == 0:
|
14 | 16 | 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)] |
16 | 21 |
|
17 |
| - # Perform breadth-first search |
18 | 22 | 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 |
24 | 29 |
|
25 |
| - return dist |
| 30 | + return mat |
0 commit comments