LeetCode 286 Walls and Gates

54 篇文章 2 订阅
13 篇文章 0 订阅

思路

思路1:暴力搜索,对每个空房间(INF)进行bfs,不过此时的bfs应该是每次向队列中加下一层的元素而不是单个元素,否则深度会算错。
时间复杂度O( n 2 ∗ m 2 n^2 * m^2 n2m2), 空间复杂度O( n ∗ m n*m nm)

思路2:
思路1为多源多终点,可以转化为单源多终点(增加一个超级源,最短路常用套路):从所有的门开始搜索,这样可以避免思路1中重复经过某些空房间。
在实现的时候忽略了超级源,直接在bfs之前将所有的门加入队列中。
时间复杂度O( n ∗ m n*m nm), 空间复杂度O( n ∗ m n*m nm)

代码

这里放的是思路2的代码

public class Solution {
    /**
     * @param rooms: m x n 2D grid
     * @return: nothing
     */
    public void wallsAndGates(int[][] rooms) {
        // write your code here
        if(rooms == null || rooms.length == 0 || rooms[0].length == 0)
            return;
        int row = rooms.length;
        int col = rooms[0].length;
        
        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();
        
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        
        // search from gates
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(rooms[i][j] == 0) {
                    qx.offer(i);
                    qy.offer(j);
                }
            }
        }
        
        // bfs: 从所有的0开始搜索
        while(!qx.isEmpty()) {
            int cx = qx.poll();
            int cy = qy.poll();
            for(int i = 0; i < 4; i++) {
                int nx = cx + dx[i];
                int ny = cy + dy[i];
                if(0 <= nx && nx < row && 0 <= ny && ny < col && rooms[nx][ny] == Integer.MAX_VALUE) {
                    qx.offer(nx);
                    qy.offer(ny);
                    rooms[nx][ny] = rooms[cx][cy] + 1;
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值