direction = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dx, dy in direction:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m:
通过以上步骤,可以有效地解决问题并生成符合要求的输出矩阵。
```python
from typing import (
List,
)
from collections import deque
class Solution:
"""
@param matrix: a 0-1 matrix
@return: return a matrix
"""
def update_matrix(self, matrix: List[List[int]]) -> List[List[int]]:
# write your code here
if not matrix:
return matrix
n, m = len(matrix), len(matrix[0])
distance = [[float('inf')] * m for _ in range(n)]
q = deque() #用deque,因为List做pop(0)复杂度是O(N)
for x in range(n):
for y in range(m):
if matrix[x][y] == 0:
distance[x][y] = 0
q.append((x,y))
direction = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while q:
x,y = q.popleft()
for dx, dy in direction:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m:
if distance[nx][ny] > distance[x][y] + 1:
distance[nx][ny] = distance[x][y] + 1
q.append((nx,ny))
return distance
```