286. Walls and Gates

286. Walls and Gates

class Solution {
    public void wallsAndGates(int[][] rooms) {
      
      Queue<int[]> queue = new LinkedList<>();
      
      for(int i = 0; i < rooms.length; i++){
        for(int j = 0; j < rooms[0].length; j++){
          if(rooms[i][j] == 0){
            queue.offer(new int[] {i, j}); // new int[]{}
              
          }
        }
      }
      while(!queue.isEmpty()){
        int[] current = queue.poll();
        int i = current[0];
        int j = current[1];
        
        int[][] dirs = {{0, 1},{0, -1}, {1,0}, {-1, 0}};  // int[][]  dirs= {{}, {}, {} }
        
        for(int index = 0; index < 4 ; index++){
          int row = i + dirs[index][0];
          int col = j + dirs[index][1];
          
          if (row < 0 || col < 0 || row >= rooms.length || col >= rooms[0].length || 
              rooms[row][col] != Integer.MAX_VALUE){
            continue;
          }
          rooms[row][col] = rooms[i][j] + 1;
          queue.offer(new int[] {row, col}); //// new int[] {}
        }
      }
    }
}

 

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

posted on 2018-08-09 17:33  猪猪&#128055;  阅读(119)  评论(0)    收藏  举报

导航