Start from gates `0`

, use `dfs`

to fill nearby rooms with distances, and return if `(i, j)`

is out of boundary or has smaller `distance`

filled.

### Version 1:

```
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, 0);
}
}
}
public void dfs(int[][] rooms, int i, int j, int d) {
if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < d) return;
rooms[i][j] = d;
dfs(rooms, i - 1, j, d + 1);
dfs(rooms, i, j - 1, d + 1);
dfs(rooms, i + 1, j, d + 1);
dfs(rooms, i, j + 1, d + 1);
}
```

### Version 2:

```
int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
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);
}
}
}
}
public void dfs(int[][] rooms, int i, int j) {
for(int[] dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if(x < 0 || x >= rooms.length || y < 0 || y >= rooms[0].length || rooms[x][y] <= rooms[i][j]) continue;
rooms[x][y] = rooms[i][j] + 1;
dfs(rooms, x, y);
}
}
```