




Sponsored
Sponsored
The BFS approach involves initializing a queue with all positions of zeros in the matrix, since the distance from any zero to itself is zero. From there, perform a level-order traversal (BFS) to update the distances of the cells that are accessible from these initial zero cells. This approach guarantees that each cell is reached by the shortest path.
Time Complexity: O(m * n), as each cell is processed at most once.
Space Complexity: O(m * n), for storing the resulting distance matrix and the BFS queue.
1from collections import deque
2
3def updateMatrix(mat):
4    rows, cols = len(mat), len(mat[0])
5    dist = [[float('inf')] * cols for _ in range(rows)]
6    queue = deque()
7
8    for r in range(rows):
9        for c in range(cols):
10            if mat[r][c] == 0:
11                dist[r][c] = 0
12                queue.append((r, c))
13
14    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
15    while queue:
16        r, c = queue.popleft()
17        for dr, dc in directions:
18            nr, nc = r + dr, c + dc
19            if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] > dist[r][c] + 1:
20                dist[nr][nc] = dist[r][c] + 1
21                queue.append((nr, nc))
22
23    return distPython leverages the deque collection for its breadth-first traversal, applying initial zero spotting and neighbor checking in order of distance update efficiency via BFS.
The dynamic programming (DP) approach updates the matrix by considering each cell from four possible directions, iterating twice over the matrix to propagate the minimum distances. First, traverse from top-left to bottom-right, and then from bottom-right to top-left, ensuring a comprehensive minimum distance calculation.
Time Complexity: O(m * n)
Space Complexity: O(m * n)
1class
The Java code executes a dual iteration: firstly to transitively propagate minimum distances towards right and downward, and then backward updating from bottom-right to fulfill comprehensive minimal distance calculation.