Created
December 29, 2024 06:38
-
-
Save marttp/c54650d2877857db12972f167ed55fd5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private static final int[][] DIRS = new int[][] { | |
new int[] {-1,0}, | |
new int[] {1,0}, | |
new int[] {0,-1}, | |
new int[] {0,1} | |
}; | |
public int[][] updateMatrix(int[][] mat) { | |
int m = mat.length; | |
int n = mat[0].length; | |
int[][] result = new int[m][n]; | |
Queue<Cell> queue = new LinkedList<>(); | |
for (int r = 0; r < m; r++) { | |
for (int c = 0; c < n; c++) { | |
if (mat[r][c] == 0) { | |
var cell = new Cell(r, c, 0); | |
queue.offer(cell); | |
} | |
} | |
} | |
while (!queue.isEmpty()) { | |
var curr = queue.poll(); | |
for (var dir : DIRS) { | |
int nr = curr.r + dir[0]; | |
int nc = curr.c + dir[1]; | |
if (isInbound(mat, nr, nc) && mat[nr][nc] == 1) { | |
mat[nr][nc] = 0; | |
int distance = curr.distance + 1; | |
result[nr][nc] = distance; | |
var cell = new Cell(nr, nc, distance); | |
queue.offer(cell); | |
} | |
} | |
} | |
return result; | |
} | |
private boolean isInbound(int[][] grid, int r, int c) { | |
return r >= 0 && r < grid.length && c >= 0 && c < grid[r].length; | |
} | |
private record Cell(int r, int c, int distance) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment