Shortest Distance from All Buildings

本文介绍了一个寻找在给定网格中建造房子以使到达所有建筑物总距离最短的问题解决方案。通过广度优先搜索算法,计算从每个建筑出发到达空地的距离,并最终确定最佳建造位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 

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


Solution

对于每一个building, 计算它能到达的每一个空地的距离。具体来讲用 dist 数组纪录,最后找最小的就好。

到下一个building时,上一个如果没有到达这个空地,那这个空地就不考虑了。这个用 canReach 数组实现。


class Solution {
    vector<pair<int,int>> dirs = { make_pair(1,0),make_pair(-1,0),make_pair(0,1),make_pair(0,-1)} ;
    
    void bfs( int curRow,int curCol,const vector<vector<int>>& grid,int numBuild,vector<vector<int>>& dist,vector<vector<int>>& canReach) {
        
        const int M = grid.size(), N = grid[0].size();
        queue<int> curLvl, nextLvl;
        unordered_set<int> visited;
        
        curLvl.push(curRow*N + curCol);
        visited.insert(curRow*N + curCol);
        int curDist = 0;
        while(!curLvl.empty()) {
            int curBuild = curLvl.front(); curLvl.pop();
            int curRow = curBuild/N, curCol = curBuild%N;
            
            for( int i = 0; i < dirs.size(); i++) {        
                int nextRow = curRow + dirs[i].first, nextCol = curCol + dirs[i].second;
                int nextBuild = nextRow * N + nextCol;
                if( nextRow >= 0 && nextRow < M && nextCol >= 0 && nextCol < N && visited.find(nextBuild) == visited.end() && grid[nextRow][nextCol] == 0 && canReach[nextRow][nextCol] == numBuild ) {
                    nextLvl.push(nextBuild);
                    visited.insert(nextBuild);
                    dist[nextRow][nextCol] += curDist + 1;
                    canReach[nextRow][nextCol] = numBuild + 1;
                }
            }
            
            if(curLvl.empty()) {
                swap(curLvl, nextLvl);
                curDist++;
            }
        }
        return;
    }
public:
    int shortestDistance(vector<vector<int>>& grid) {
        if(grid.empty() || grid[0].empty()) return 0;
        
        const int M = grid.size(), N = grid[0].size();
        vector<vector<int>> dist( M, vector<int>(N, 0) );
        vector<vector<int>> canReach( M, vector<int>(N, 0) );
        
        int numBuild = 0;
        for( int row = 0; row < M; row++ ){
            for( int col = 0; col < N; col++){
                if( grid[row][col] == 1 ) {
                    bfs(row, col, grid, numBuild++, dist, canReach );
                }
            }
        }
        
        int rst = INT_MAX;
        for( int row = 0; row < M; row++ ){
            for( int col = 0; col < N; col++){
                if(canReach[row][col] == numBuild ) {
                    rst = min( rst, dist[row][col]);
                }
            }
        }
        return rst==INT_MAX ? -1 : rst;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值