




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.
1import java.util.LinkedList;
2import java.util.Queue;
3
4class Solution {
5    public int[][] updateMatrix(int[][] mat) {
6        int m = mat.length, n = mat[0].length;
7        int[][] dist = new int[m][n];
8        Queue<int[]> q = new LinkedList<>();
9
10        for (int i = 0; i < m; i++) {
11            for (int j = 0; j < n; j++) {
12                if (mat[i][j] == 0) {
13                    dist[i][j] = 0;
14                    q.offer(new int[] {i, j});
15                } else {
16                    dist[i][j] = Integer.MAX_VALUE;
17                }
18            }
19        }
20
21        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
22        while (!q.isEmpty()) {
23            int[] cell = q.poll();
24            for (int[] d : directions) {
25                int r = cell[0] + d[0], c = cell[1] + d[1];
26                if (r >= 0 && r < m && c >= 0 && c < n && dist[r][c] > dist[cell[0]][cell[1]] + 1) {
27                    dist[r][c] = dist[cell[0]][cell[1]] + 1;
28                    q.offer(new int[] {r, c});
29                }
30            }
31        }
32
33        return dist;
34    }
35}JAVA employs a similar BFS strategy, aided by a queue data structure, maintaining a grid of distances to fill based on initial zero positions and valid neighborings.
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)
1function
JavaScript applies dynamic programming with two matrix processing passed, ensuring a concise approach to minimum distance setting based on initial zero indexes and step-optimal path tracking through reversed iteration.