```
public class Solution {
//BFS
public void wallsAndGates(int[][] rooms) {
if(rooms == null || rooms.length == 0) {
return;
}
int row = rooms.length;
int col = rooms[0].length;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(rooms[i][j] == 0) {
BFS(rooms, i, j);
}
}
}
}
private void BFS(int[][] rooms, int m, int n) {
int row = rooms.length;
int col = rooms[0].length;
int cord = m * col + n;
int[][] visited = new int[row][col];
Queue<Integer> qu = new LinkedList<Integer>();
qu.offer(cord);
visited[m][n] = 1;
int dis = 0;
int[] dx = {1, -1, 0, 0};//up, down, right, left
int[] dy = {0, 0, 1, -1};
while(!qu.isEmpty()) {
int size = qu.size();
for(int i = 0; i < size; i++) {
int tmp = qu.poll();
int x = tmp / col;
int y = tmp % col;
rooms[x][y] = Math.min(rooms[x][y], dis);
for(int k = 0; k < 4; k++) {
int newX = x + dx[k];
int newY = y + dy[k];
if(newX < 0 || newX >= row || newY < 0 || newY >= col) {
continue;
}
if(visited[newX][newY] == 1) {
continue;
}
if(rooms[newX][newY] == -1) {
continue;
}
qu.offer(newX * col + newY);
visited[newX][newY] = 1;
}
}
dis++;
}
}
```

}