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.
对每一个1做bfs,然后更新dist里面的距离。小trick是第一个搜的是0, 第二次搜的是1,不然的话要用visited数组来记录。
bfs里面每一个min刚进去的时候都要更新成最大值。
public class Solution {
int min = Integer.MAX_VALUE;
int[] dx = new int[]{1, -1, 0, 0};
int[] dy = new int[]{0, 0, -1, 1};
public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0){
return 0;
}
int m = grid.length;
int n = grid[0].length;
int[][] dist = new int[m][n];
int start = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == 1){
bbb(grid, i, j, dist, start--);
}
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
public void bbb(int[][] grid, int m, int n, int[][] dist, int start){
Queue<int[]> q = new LinkedList<int[]>();
q.offer(new int[]{m,n});
int level = 1;
min = Integer.MAX_VALUE;
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i<size; i++){
int[] cur = q.poll();
for(int pos = 0; pos < 4; pos++){
int x = cur[0] + dx[pos];
int y = cur[1] + dy[pos];
if(x>=0 && y>=0 && x<grid.length && y<grid[0].length){
if(grid[x][y] == start){
dist[x][y] += level;
grid[x][y] = start - 1;
q.offer(new int[]{x, y});
min = Math.min(min, dist[x][y]);
}
}
}
}
level++;
}
}
}