Description
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 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j]
is either0
or1
.- There is at least one
0
inmat
.
Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/
Solution
Python3
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
rows, cols = len(mat), len(mat[0])
queue = deque()
dist = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if mat[i][j] == 0:
queue.append((i, j))
mat[i][j] = -1
d = 0
while queue:
N = len(queue)
for _ in range(N):
x, y = queue.popleft()
dist[x][y] = d
for dx, dy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if 0 <= dx < rows and 0 <= dy < cols and mat[dx][dy] != -1:
mat[dx][dy] = -1
queue.append((dx, dy))
d += 1
return dist