Skip to content

Commit 70b7507

Browse files
committed
Time: 1407 ms (5.03%), Space: 46.7 MB (15.50%) - LeetHub
1 parent 5801649 commit 70b7507

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

0542-01-matrix/0542-01-matrix.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution { // DFS, TC: O(n*m)
2+
private int n, m;
3+
private int[][] dir = {{-1,0}, {1,0}, {0,-1}, {0, 1}};
4+
5+
public int[][] updateMatrix(int[][] mat) {
6+
this.m = mat.length;
7+
this.n = mat[0].length;
8+
boolean[][] visited = new boolean[m][n];
9+
10+
for (int i = 0; i < m; i++) {
11+
for (int j = 0; j < n; j++) {
12+
if(mat[i][j] == 0 && !visited[i][j]) {
13+
solve(i, j, visited, mat, 0);
14+
}
15+
}
16+
}
17+
return mat;
18+
}
19+
20+
private void solve (int i, int j, boolean[][] visited, int[][] mat, int lvl) {
21+
if (i < 0 || i >= m || j < 0 || j >= n || (mat[i][j]==0 && lvl != 0)) { // out of bounds check or if cell contains zero & it is not the same cell where we started
22+
return;
23+
}
24+
25+
if (visited[i][j] && mat[i][j] <= lvl) { // if cell is already been visited & distance so far is greater than already calculated one, so no need to calculate further
26+
return;
27+
}
28+
29+
visited[i][j] = true;
30+
31+
mat[i][j] = lvl;
32+
33+
for (int[] d : dir) {
34+
int _m = i + d[0];
35+
int _n = j + d[1];
36+
37+
solve(_m, _n, visited, mat, lvl+1);
38+
}
39+
40+
}
41+
}

0 commit comments

Comments
 (0)