class Solution {
public int[] pos = {0, 1, 0, -1, 0};
public void wallsAndGates(int[][] rooms) {
for (int i = 0; i < rooms.length; i++) {
for (int j = 0; j < rooms[0].length; j++) {
if (rooms[i][j] == 0) {
dfs(rooms, i, j);
}
}
}
}
private void dfs(int[][] rooms, int i, int j) {
for (int k = 0; k < 4; k++) {
int p = i + pos[k], q = j + pos[k + 1];
if (0 <= p && p < rooms.length && 0 <= q && q < rooms[0].length && rooms[p][q] > rooms[i][j] + 1) {
rooms[p][q] = rooms[i][j] + 1;
dfs(rooms, p, q);
}
}
}
}
This position index array initialization is interesting. Also, how we judge the minimum distance is important rooms[p][q] > rooms[i][j] + 1. Here we start from the gates!
BFS (slower):
class Solution {
public int[] pos = {0, 1, 0, -1, 0};
public void wallsAndGates(int[][] rooms) {
if (rooms.length == 0 || rooms[0].length == 0) return ;
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++) {
if (rooms[i][j] == 0) queue.add(new int[]{i, j});
}
}
while (!queue.isEmpty()) {
int[] top = queue.remove();
int row = top[0], col = top[1];
if (row > 0 && rooms[row - 1][col] == Integer.MAX_VALUE) {
rooms[row - 1][col] = rooms[row][col] + 1;
queue.add(new int[]{row - 1, col});
}
if (row < rooms.length - 1 && rooms[row + 1][col] == Integer.MAX_VALUE) {
rooms[row + 1][col] = rooms[row][col] + 1;
queue.add(new int[]{row + 1, col});
}
if (col > 0 && rooms[row][col - 1] == Integer.MAX_VALUE) {
rooms[row][col - 1] = rooms[row][col] + 1;
queue.add(new int[]{row, col - 1});
}
if (col < rooms[0].length - 1 && rooms[row][col + 1] == Integer.MAX_VALUE) {
rooms[row][col + 1] = rooms[row][col] + 1;
queue.add(new int[]{row, col + 1});
}
}
}
}
DFS:
This position index array initialization is interesting. Also, how we judge the minimum distance is important
rooms[p][q] > rooms[i][j] + 1
. Here we start from the gates!BFS (slower):