2015年9月28日星期一

Walls and Gates

 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

public class Solution {
    public void wallsAndGates(int[][] rooms) {
        if (rooms == null || rooms.length == 0 || rooms[0].length == 0) return;
        LinkedList<int[]> queue = new LinkedList<>();
        int m = rooms.length;
        int n = rooms[0].length;
       
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (rooms[i][j] == 0) {
                    queue.add(new int[] {i, j});
                }
            }
        }
        int dis = 0;
        while (!queue.isEmpty()) {
            int count = queue.size();
            while (count-- > 0) {
                int[] p = queue.poll();
                int x = p[0];
                int y = p[1];
                if (x - 1 >= 0 &&rooms[x - 1][y] == Integer.MAX_VALUE) {
                    rooms[x-1][y] = dis + 1;
                    queue.add(new int[] {x - 1, y});
                }
                if (x + 1 < m && rooms[x+1][y] == Integer.MAX_VALUE) {
                    rooms[x+1][y] = dis + 1;
                    queue.add(new int[] {x+1, y});
                }
                if (y - 1 >= 0 && rooms[x][y-1] == Integer.MAX_VALUE) {
                    rooms[x][y-1] = dis + 1;
                    queue.add(new int[] {x, y - 1});
                }
                if (y + 1 < n && rooms[x][y + 1] == Integer.MAX_VALUE) {
                   rooms[x][y+1] = dis + 1;
                    queue.add(new int[] {x, y + 1});
                }
            }
            dis++;
        }
    }
}

没有评论:

发表评论