542. 01 Matrix#

Approach#

Using BFS with source as all cells containing 0s and updating the distance values until all paths are exhausted.

Code#

 1public int[][] updateMatrix(int[][] mat) {
 2  int m = mat.length, n = mat[0].length;
 3  Queue<int[]> q = new LinkedList<>();
 4
 5  for (int i = 0; i < m; i++) {
 6    for (int j = 0; j < n; j++) {
 7      if (mat[i][j] == 0) {
 8        q.add(new int[] { i, j });
 9      } else {
10        mat[i][j] = Integer.MAX_VALUE;
11      }
12    }
13  }
14
15  int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
16
17  while (!q.isEmpty()) {
18    int[] head = q.remove();
19    int i = head[0];
20    int j = head[1];
21
22    for (int k = 0; k < dirs.length; k++) {
23      int x = i + dirs[k][0];
24      int y = j + dirs[k][1];
25
26      if (x < 0 || x == m || y < 0 || y == n) continue;
27      if (mat[x][y] <= mat[i][j] + 1) continue;
28
29      mat[x][y] = mat[i][j] + 1;
30      q.add(new int[] { x, y });
31    }
32  }
33
34  return mat;
35}

Time complexity

Space complexity

\(\mathcal{O}(m*n)\)

\(\mathcal{O}(m*n)\)