




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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public int[][] UpdateMatrix(int[][] mat) {
6        int m = mat.Length, n = mat[0].Length;
7        int[][] dist = new int[m][];
8        for (int i = 0; i < m; i++) {
9            dist[i] = new int[n];
10            Array.Fill(dist[i], int.MaxValue);
11        }
12
13        Queue<(int, int)> q = new Queue<(int, int)>();
14
15        for (int i = 0; i < m; i++) {
16            for (int j = 0; j < n; j++) {
17                if (mat[i][j] == 0) {
18                    dist[i][j] = 0;
19                    q.Enqueue((i, j));
20                }
21            }
22        }
23
24        int[][] directions = new int[][] {
25            new int[] {1, 0},
26            new int[] {-1, 0},
27            new int[] {0, 1},
28            new int[] {0, -1}
29        };
30
31        while (q.Count > 0) {
32            var (row, col) = q.Dequeue();
33            foreach (var direction in directions) {
34                int newRow = row + direction[0], newCol = col + direction[1];
35                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && dist[newRow][newCol] > dist[row][col] + 1) {
36                    dist[newRow][newCol] = dist[row][col] + 1;
37                    q.Enqueue((newRow, newCol));
38                }
39            }
40        }
41
42        return dist;
43    }
44}C# utilizes queues similarly to other languages for BFS, with direction arrays supporting exploration through all bounded paths while updating minimal distances as it's processed.
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)
1#
In this C code, distance calculation progresses first from the top-left to bottom-right. We then perform a second pass from bottom-right to top-left to integrate the shortest distances possible from alternate directions. The use of INT_MAX - 1 is a sufficient surrogate for infinity.