[LeetCode] Walls and Gates

本文介绍了一种使用广度优先搜索(BFS)算法来解决迷宫中每个空房间到最近出口的距离问题的方法。该算法首先将所有出口坐标加入队列,并从这些点开始遍历周围的空房间,更新其到出口的距离。通过这种方式逐步扩展直至所有可达区域都被标记。

Walls and Gates

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 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.

BFS

Time Complexity
O(MN)
Space Complexity
O(N)

思路

Push all gates into queue first. Then for each gate update its neighbor cells and push them to the queue. For visited, I just check if the matrixi for 4 directions is bigger than the current matrixi, if it is bigger means it hasn't been visited.

代码

public void wallsAndGates(int[][] rooms) {
    //corner case
    if(rooms == null || rooms.length == 0 || rooms[0] == null || rooms[0].length == 0) return;
    Queue<int[]> queue = new LinkedList<int[]>();
    int step = 1;
    int rows = rooms.length, cols = rooms[0].length;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(rooms[i][j] == 0) queue.offer(new int[]{i, j});
        }
    }
    
    int[][] directions = new int[][]{{-1, 0},{1, 0},{0,1},{0,-1}};
    
    while(!queue.isEmpty()){
        int size = queue.size();
        for(int i = 0; i < size; i++){
            int[] cur = queue.poll();
            for(int[] dir : directions){
                int x = cur[0] + dir[0];
                int y = cur[1] + dir[1];
                if(x >= 0 && x < rows && y >= 0 && y < cols && rooms[x][y] > rooms[cur[0]][cur[1]]){
                    rooms[x][y] = step;
                    queue.offer(new int[]{x,y});
                }
            }
        }
        step++;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值