




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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#define QUEUE_SIZE 10000
6
7int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
8
9typedef struct {
10    int row, col;
11} Point;
12
13int** updateMatrix(int** mat, int matSize, int* matColSize, int* returnSize, int** returnColumnSizes) {
14    *returnSize = matSize;
15    *returnColumnSizes = malloc(sizeof(int) * matSize);
16    int n = matColSize[0];
17    int** dist = (int**)malloc(sizeof(int*) * matSize);
18    for (int i = 0; i < matSize; ++i) {
19        dist[i] = (int*)malloc(sizeof(int) * n);
20        (*returnColumnSizes)[i] = n;
21        for (int j = 0; j < n; ++j) {
22            dist[i][j] = mat[i][j] == 0 ? 0 : INT_MAX;
23        }
24    }
25
26    Point queue[QUEUE_SIZE];
27    int front = 0, back = 0;
28    for (int i = 0; i < matSize; ++i) {
29        for (int j = 0; j < n; ++j) {
30            if (mat[i][j] == 0) {
31                queue[back++] = (Point){i, j};
32            }
33        }
34    }
35
36    while (front < back) {
37        Point p = queue[front++];
38        for (int d = 0; d < 4; ++d) {
39            int r = p.row + directions[d][0];
40            int c = p.col + directions[d][1];
41            if (r >= 0 && r < matSize && c >= 0 && c < n && dist[r][c] > dist[p.row][p.col] + 1) {
42                dist[r][c] = dist[p.row][p.col] + 1;
43                queue[back++] = (Point){r, c};
44            }
45        }
46    }
47
48    return dist;
49}In the C implementation, we use a queue to perform a BFS starting from all cells with 0. We then update neighboring cells with the smallest distance possible, propagating the minimum distances to eventually fill out the entire matrix with correct values.
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)
1def updateMatrix
Python executes a very similar dual-pass strategy, processing twice to cover and update each potential directional influence, ensuring minimal path discovery at each matrix entry point.