Skip to content

Walls and Gates

Tim_Gao edited this page Sep 17, 2016 · 2 revisions

    -1 - A wall or an obstacle.
    0 - A gate.
    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.length == 0 || rooms[0].length == 0){
            return;
        }
        LinkedList<int[]> q1 = new LinkedList<>(), q2 = new LinkedList<>();
        for (int i=0; i<rooms.length; ++i){
            for (int j=0; j<rooms[0].length; ++j){
                if(rooms[i][j] == 0){
                    q1.add(new int[]{i, j});
                }
            }
        }
        int dis = 1;
        while (!q1.isEmpty()){
            q2 = q1;
            q1 = new LinkedList<>();
            while (!q2.isEmpty()){
                int[] crt = q2.getFirst();
                q2.removeFirst();
                int x = crt[0], y = crt[1];
                if(x-1>=0 && rooms[x-1][y] == Integer.MAX_VALUE){
                    rooms[x-1][y] = dis;
                    q1.add(new int[]{x-1, y});
                }
                if(x+1 < rooms.length && rooms[x+1][y] == Integer.MAX_VALUE){
                    rooms[x+1][y] = dis;
                    q1.add(new int[]{x+1, y});
                }
                if (y-1>=0 && rooms[x][y-1] == Integer.MAX_VALUE){
                    rooms[x][y-1] = dis;
                    q1.add(new int[]{x, y-1});
                }
                if (y+1<rooms[0].length && rooms[x][y+1] == Integer.MAX_VALUE){
                    rooms[x][y+1] = dis;
                    q1.add(new int[]{x, y+1});
                }
            }
            ++dis;
        }
    }
}

Clone this wiki locally