286. Walls and Gates

Problem:
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

Analysis:

Standard reverse BFS. 01 Matrix 的马甲题。

Solution:

class Solution {
    public void wallsAndGates(int[][] rooms) {
        if (rooms == null || rooms.length == 0 || rooms[0].length == 0)
            return;

        int m = rooms.length;
        int n = rooms[0].length;
        int[][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (rooms[i][j] == 0) {
                    queue.offer(new int[]{i, j});    
                }
                
        }
        int dis = 0;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            dis++;
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                int x = cur[0];
                int y = cur[1];
                for (int[] dir: dirs) {
                    int newx = x + dir[0];
                    int newy = y + dir[1];
                    int newIndex = newx * n + newy;
                    if (newx < 0 || newx >= m || newy < 0 || newy >= n) 
                        continue;
                    if (rooms[newx][newy] != 2147483647 )
                        continue;
                    queue.offer(new int[]{newx, newy});
                    rooms[newx][newy] = dis;
                }   
            }
            
        }
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List