317. 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.

一刷
思路: 通过BFS, 以building为起点计算出每个empty space到所有building的距离,然后从其中取出最小的即为满足要求的点。

class Solution {
    class Tuple{
        int x;
        int y;
        int dist;
        Tuple(int x, int y, int dist){
            this.x = x;
            this.y = y;
            this.dist = dist;
        }
    }
    
    int[][] dirs = {{1, 0},{-1, 0},{0, 1},{0, -1}};
    
    public int shortestDistance(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        List<Tuple> building = new ArrayList<>();
        
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j] == 1){
                    building.add(new Tuple(i, j, 0));
                grid[i][j] = -grid[i][j];
                }
            }
        }
        
        //BFS
        int[][] dist = new int[m][n];
        for(int i=0; i<building.size(); i++){
            bfs(building.get(i), i,grid, dist, m, n);
        }
        
        //find the minimum
        int res = Integer.MAX_VALUE;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j] == building.size())
                    res = Math.min(res, dist[i][j]);
            }
        }
        
        return res;
    }
    
    
    private void bfs(Tuple root, int k,int[][] grid, int[][] dist, int m, int n){
        Queue<Tuple> queue = new ArrayDeque<>();
        queue.add(root);
        while(!queue.isEmpty()){
            Tuple cur = queue.poll();
            dist[cur.x][cur.y] += cur.dist;
            for(int[] dir : dirs){
                int x = cur.x + dir[0];
                int y = cur.y + dir[0];
                if(x>=0 && y>=0 && x<m && y<n && grid[x][y] == k){//避免重复加入, 对于同一个building, 只加入一次。
                    grid[x][y]++;
                    queue.add(new Tuple(x, y, cur.dist+1));
                }
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容