leetcode286 - Walls and Gates - medium

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 3 -1 0 1
INF INF INF -1 -> 2 2 1 -1
INF -1 INF -1 1 -1 2 -1
0 -1 INF INF 0 -1 3 4

BFS。
先让所有的注水点0进q,接下来开始往INF拓展,如果占到了就不能再让别人占了,因为先占到就说明是最近的,数字已经准了。
和前一题01 matrix非常类似,区别只在bfs的时候加上看到-1不允许入队即可。这样就能保证从0开始扩展的路径不通过-1。同时本题自动把可走路径初始化为INF了,那就不需要visited数组了,直接看这个INF被划去没有就知道有没有0出发的源泉占领这里了。

实现:

class Solution {
    public void wallsAndGates(int[][] rooms) {
        if (rooms == null || rooms.length == 0 || rooms[0].length == 0) {
            return;
        }
        
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();

        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[0].length; j++) {
                if (rooms[i][j] == 0) {
                    qx.offer(i);
                    qy.offer(j);
                }
            }
        }
        
        int dist = 0;
        while (!qx.isEmpty()) {             
            dist++;
            int size = qx.size();
            for (int cnt = 0; cnt < size; cnt++) {
                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 (nx < 0 || nx >= rooms.length || ny < 0 
                        || ny >= rooms[0].length || rooms[nx][ny] != Integer.MAX_VALUE) {
                        continue;
                    }
                    rooms[nx][ny] = dist;
                    qx.offer(nx);
                    qy.offer(ny);
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/jasminemzy/p/9644263.html
今日推荐