We need to find the distance of the nearest 0 for each cell in a binary matrix. The straightforward approach could involve iterating over every cell and computing the distance to every zero, which would be quite inefficient. Instead, we can utilize a Breadth-First Search (BFS) approach to achieve a more efficient solution.
Here’s the implementation in Python:
from collections import deque
def updateMatrix(matrix):
if not matrix or not matrix[0]:
return []
rows, cols = len(matrix), len(matrix[0])
dist = [[float('inf')] * cols for _ in range(rows)]
queue = deque()
# Enqueue all 0 cells and set their distance to 0
for r in range(rows):
for c in range(cols):
if matrix[r][c] == 0:
dist[r][c] = 0
queue.append((r, c))
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if dist[nr][nc] > dist[r][c] + 1:
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return dist
dist
initialized to infinity.dist
matrix.With this approach, we efficiently compute the distance of the nearest 0 for each cell in the matrix.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?