Walls and Gates (LeetCode)-这是一道经典题

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.

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});
            }
        }  
    }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值