[LeetCode]Walls and Gates

Walls and Gates

You are given a m x n 2D grid initialized with these three possible values.

  1. -1 - A wall or an obstacle.

  2. 0 - A gate.

  3. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.

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.

For 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, DFS和DP,尤其是求类似最短距离的问题首先考虑的是BFS。同时,这道题是在房间里填充最近门与之距离,所以我们可以考虑从门开始BFS,一层一层计算门到房间的距离。

最优的解法应该是只用遍历一次矩阵。直接先扫一遍矩阵把所有门push到queue里,然后BFS,这样的好处对于房间而言第一次visit到的就是最短距离,因为是BFS。另外一种方法是对每个门分别BFS,这样的话有个不好的地方时我们得需要比较之前BFS的距离,然后得出最小值,这样的时间复杂度也高很多,因为相当于遍历矩阵K次,K表示门的个数。

另外,由于每个门我们只visit一次,这里我们可以直接根据门里的值来判断之前是否visit过,如果值不是INF, 表示已被visit过,不用再visit。

复杂度

time: O(MN), space: O(MN)

代码

public class Solution {
    public void wallsAndGates(int[][] rooms) {
        Queue<int[]> queue = new LinkedList<int[]>();
        int rows = rooms.length;
        if (rows == 0) {
            return;
        }
        int cols = rooms[0].length;
        
        // 找出所有BFS的起始点
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (rooms[i][j] == 0) {
                    queue.add(new int[]{i, j});
                }
            }
        }
        
        // 定义下一步的位置
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        
        // 开始BFS
        while (!queue.isEmpty()) {
            int[] top = queue.remove();
            for (int k = 0; k < dirs.length; k++) {
                int x = top[0] + dirs[k][0];
                int y = top[1] + dirs[k][1];
                if (x >= 0 && x < rows && y >= 0 && y < cols && rooms[x][y] == Integer.MAX_VALUE) {
                    rooms[x][y] = rooms[top[0]][top[1]] + 1;
                    queue.add(new int[]{x, y});
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值