You are given a m x n 2D grid initialized with these three possible values.
-1
- A wall or an obstacle.0
- A gate.INF
- Infinity means an empty room. We use the value231 - 1 = 2147483647
to representINF
as you may assume that the distance to a gate is less than2147483647
.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF
.
Example:
Given the 2D grid:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
算法思想:采用BFS,先将所有的gate位置放到Queue中,对Queue进行操作,poll第一个元素,因为是广度优先,元素周围有四个元素,根据边界判断邻居元素的有效性,同时访问过的元素和wall元素是没必要访问的,按照最一般最好理解的做法是,把访问过的元素放到一个set 1中,把wall元素放到另一个set 2中,在遍历neighbors的时候,如果发现在set 1或者set 2中,就跳过,就这道题来说有个取巧的办法,如果元素值不等于INF,说明是访问过的元素或者是wall元素。邻居有效元素根据父node更新自己相对gate的值,然后将其入队,四个邻居元素判断过后,开始新一轮出队操作,直到queue为空,此时,所有房间到gate的最短距离也都求解出来了。
class Solution {
public static final int GATE = 0;
public static final int EMPTY = Integer.MAX_VALUE;
public static final List<int[]> DIRECTIONS = Arrays.asList(
new int[]{1,0},
new int[]{-1, 0},
new int[]{0,1},
new int[]{0, -1});
public void wallsAndGates(int[][] rooms) {
int m = rooms.length;//行
if (m == 0) return;
int n = rooms[0].length;//列
Queue<int[]> queue = new LinkedList();
//把所有门gate的节点位置都放到队列中
/*
* 为什么不是,先从一个gate,BFS完以后,再遍历另一个gate呢
* 如果,这样做的话,找到从房间到门的距离就不是最短距离了。
*/
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (rooms[i][j] == GATE) {
queue.offer(new int[] {i,j});
}
}
}
//BFS
while (!queue.isEmpty()) {
int[] pos = queue.poll();
int r = pos[0];
int c = pos[1];
for (int[] direction : DIRECTIONS) {
int row = r + direction[0];
int col = c + direction[1];
//超出范围的和访问过的跳过
if (row < 0 || row > m-1 || col < 0 || col > n-1 || rooms[row][col] != EMPTY) {
continue;
}
rooms[row][col] = rooms[r][c] + 1;
queue.offer(new int[]{row,col});
}
}
}
}