Leetcode刷题 2021.03.30
Leetcode286 墙与门
你被给定一个 m × n 的二维网格 rooms ,网格中有以下三种可能的初始化值:
-1 表示墙或是障碍物
0 表示一扇门
INF 无限表示一个空的房间。然后,我们用 231 - 1 = 2147483647 代表 INF。你可以认为通往门的距离总是小于 2147483647 的。
你要给每个空房间位上填上该房间到 最近门的距离 ,如果无法到达门,则填 INF 即可。
又是经典的BFS板子题,常做常新~。
class Solution {
int[][] directions = new int[][]{
{
-1, 0}, {
1, 0}, {
0, -1}, {
0, 1}};
public void wallsAndGates(int[][] rooms) {
//BFS模板题
Queue<int[]> queue = new LinkedList<>();
int m = rooms.length, n = rooms[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (rooms[i][j] == 0){
queue.offer(new int[]{
i, j});
}
}
}
int count = 1;
while (!queue.isEmpty()){