Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 13, 2016 20:09
Show Gist options
  • Select an option

  • Save cangoal/3817872769f8428e5d18d18c88fcec3e to your computer and use it in GitHub Desktop.

Select an option

Save cangoal/3817872769f8428e5d18d18c88fcec3e to your computer and use it in GitHub Desktop.
LeetCode - Shortest Distance from All Buildings
// You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
// Each 0 marks an empty land which you can pass by freely.
// Each 1 marks a building which you cannot pass through.
// Each 2 marks an obstacle which you cannot pass through.
// For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
// 1 - 0 - 2 - 0 - 1
// | | | | |
// 0 - 0 - 0 - 0 - 0
// | | | | |
// 0 - 0 - 1 - 0 - 0
// The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
// Note:
// There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int totalBuildings = countBuildings(grid);
int minSteps = Integer.MAX_VALUE;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 0){
minSteps = Math.min(minSteps, bfs(grid, i, j, totalBuildings));
}
}
}
return minSteps == Integer.MAX_VALUE ? -1 : minSteps;
}
private int countBuildings(int[][] grid){
int res = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 1) res++;
}
}
return res;
}
private int bfs(int[][] grid, int i, int j, int totalBuildings){
if(totalBuildings == 0) return Integer.MAX_VALUE;
int m = grid.length, n = grid[0].length;
int[][] visited = new int[m][n];
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(i * n + j);
int step = 0, foundBuildings = 0, totalSteps = 0, size = queue.size();
while(!queue.isEmpty()){
int val = queue.poll();
size--;
int x = val / n, y = val % n;
if(visited[x][y] == 0){
visited[x][y] = 1;
if(grid[x][y] == 0){
if(x - 1 >= 0) queue.offer((x-1) * n + y);
if(y - 1 >= 0) queue.offer(x * n + y - 1);
if(x + 1 < m) queue.offer((x+1) * n + y);
if(y + 1 < n) queue.offer(x * n + y + 1);
} else if(grid[x][y] == 1){
foundBuildings++;
totalSteps += step;
if(foundBuildings == totalBuildings) return totalSteps;
}
}
if(size == 0){
step++;
size = queue.size();
}
}
return Integer.MAX_VALUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment