public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.length == 0 || rooms[0].length == 0) {
int m = rooms.length, n = rooms[0].length;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
queue.add(new int[] {i, j});
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int[] cell = queue.remove();
int curRow = cell[0], curCol = cell[1];
for (int[] direction : directions) {
int nextRow = curRow + direction[0];
int nextCol = curCol + direction[1];
if (isValid(rooms, nextRow, nextCol)) {
rooms[nextRow][nextCol] = rooms[curRow][curCol] + 1;
queue.add(new int[] {nextRow, nextCol});
public boolean isValid(int[][] matrix, int nextRow, int nextCol) {
return nextRow >= 0 && nextRow < matrix.length && nextCol >= 0 && nextCol < matrix[0].length && matrix[nextRow][nextCol] == Integer.MAX_VALUE;