Find Shortest distance from a guard in a Bank.

Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’ represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix with their shortest distance from a guard, without being able to go through any walls. Also, replace the guards with 0 and walls with -1 in output matrix.

Expected Time complexity is O(MN) for a M x N matrix.

Examples:

O ==> Open Space
G ==> Guard
W ==> Wall

Input: 
  O  O  O  O  G
  O  W  W  O  O
  O  O  O  W  O
  G  W  W  W  O
  O  O  O  O  G

Output:  
  3  3  2  1  0
  2 -1 -1  2  1
  1  2  3 -1  2
  0 -1 -1 -1  1
  1  2  2  1  0




public char[][] fillDistance(char[][] matrix){
  // sanity check
  if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return null;
  int[][] dirs = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
  
  Queue<int[]> queue = new LinkedList<>();
  for(int i = 0; i < matrix.length; i++){
    for(int j = 0; j < matrix[0].length; j++){
      if(matrix[i][j] == 'G'){
        queue.offer(new int[]{i, j});
      }
    }
  }
  int distance = 1;
  
  while(!queue.isEmpty()){
    int size = queue.size();
    for(int j = 0; j < size; j++){
      int[] cur = queue.poll();
      int row = cur[0];
      int col = cur[1];
      matrix[row][col] = (char)distance; //
      
      for(int[] dir : dirs){
        int newRol = row + dir[0];
        int newCol = col + dir[1];
        
        // check boundary and if it's O
        if(newRow < 0 || newCol < 0 || newRow >= matrix.length || newCol >= matrix[0].length || matrix[newRow][newCol] != 'O') continue;
        queue.offer(new int[]{newRow, newCol});
      }
    }
    distance++;// not placed above 
  }
  
  // change the G to 0 and W to -1
  
  for(int r = 0; r < matrix.length; r++){   // can i use i here, since it's used above ? 
    for(int c = 0; c < matrix[0].length; c++){
      if(matrix[r][c] == 'G') matrix[r][c] == '0';
      if(matrix[r][c] == 'W') matrix[r][c] == '-1';
    }
  }
  return matrix;
}
    

 

 

posted on 2018-08-11 03:51  猪猪&#128055;  阅读(386)  评论(0)    收藏  举报

导航