LeetCode刷题实战317:离建筑物最近的距离
算法的重要性,我就不多說了吧,想去大廠,就必須要經過基礎知識和業(yè)務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?離建筑物最近的距離,我們先來看題面:
https://leetcode-cn.com/problems/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.
你是個房地產開發(fā)商,想要選擇一片空地 建一棟大樓。你想把這棟大樓夠造在一個距離周邊設施都比較方便的地方,通過調研,你希望從它出發(fā)能在 最短的距離和 內抵達周邊全部的建筑物。請你計算出這個最佳的選址到周邊全部建筑物的 最短距離和。
注意:
你只能通過向上、下、左、右四個方向上移動。
給你一個由 0、1 和 2 組成的二維網格,其中:
0 代表你可以自由通過和選擇建造的空地
1 代表你無非通行的建筑物
2 代表你無非通行的障礙物
示例
解題
主要思路:
(1)使用廣度優(yōu)先搜索,從每個建筑出發(fā),找能到達的各個空地的距離,從所有建筑都能到達的空地中選擇一個距離最小的值;
(2)使用兩個數組進行輔助,一個用來輔助記錄從建筑出發(fā)的到各個空地的距離,一個用來輔助記錄各個建筑到某個空地的距離和,最后從其中選擇一個所有的建筑都能到達的空地的最小值作為結果;
class?Solution?{ public:int?shortestDistance(vector<vector<int>>& grid)?{int?rows=grid.size();int?cols=grid[0].size();//記錄各個建筑到各個空格的距離vector<vector<int>> dist(rows,vector<int>(cols,0));//記錄各個建筑能到各個空格的距離之和vector<vector<int>> sum_dist(rows,vector<int>(cols,0));//可以移動的方向vector<vector<int>> step={{0,1},{0,-1},{1,0},{-1,0}};//主要標識之前的各個建筑都能到達的空格,這樣減少計算量int?times=0;int?res=INT_MAX;//從當前各個建筑都能到達的空地中,找出最小的距離之和值//遍歷各個位置for(int?i=0;i<rows;++i){for(int?j=0;j<cols;++j){if(grid[i][j]==1){//若當前位置是建筑,從該位置開始進行廣度優(yōu)先搜索res=INT_MAX;//初始化該值pair<int,int> cur_pos;//輔助變量queue<pair<int,int>> q;//廣度優(yōu)先搜索存儲結構q.push({i,j});//初始化while(!q.empty()){cur_pos=q.front();//當前點q.pop();for(int?k=0;k<step.size();++k){//嘗試的四個方向//嘗試的位置int?x=cur_pos.first+step[k][0];int?y=cur_pos.second+step[k][1];//若當前位置沒有越界,既有效,且之前的各個建筑都能夠到達if(x>=0&&x<rows&&y>=0&&y<cols&&grid[x][y]==times){//則更新當前距離dist[x][y]=dist[cur_pos.first][cur_pos.second]+1;//更新對應的距離之和sum_dist[x][y]+=dist[x][y];//保存最小的距離和res=min(res,sum_dist[x][y]);//對應的值減一,標識當前建筑也訪問過--grid[x][y];//壓入當前位置q.push({x,y});}}}//若該值沒有變化,說明該建筑不能到達之前建筑都到達過的空地,則直接返回-1if(res==INT_MAX){return?-1;}//標識當前建筑也訪問過--times;}}}return?res;} };好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉發(fā)吧,你們的支持是我最大的動力 。
上期推文:
LeetCode1-300題匯總,希望對你有點幫助!
LeetCode刷題實戰(zhàn)301:刪除無效的括號
LeetCode刷題實戰(zhàn)302:包含全部黑色像素的最小矩陣
LeetCode刷題實戰(zhàn)303:區(qū)域和檢索 - 數組不可變
LeetCode刷題實戰(zhàn)304:二維區(qū)域和檢索 - 矩陣不可變
LeetCode刷題實戰(zhàn)305:島嶼數量II
LeetCode刷題實戰(zhàn)306:累加數
LeetCode刷題實戰(zhàn)307:區(qū)域和檢索 - 數組可修改
LeetCode刷題實戰(zhàn)308:二維區(qū)域和檢索 - 可變
LeetCode刷題實戰(zhàn)309:最佳買賣股票時機含冷凍期
LeetCode刷題實戰(zhàn)310:最小高度樹
LeetCode刷題實戰(zhàn)311:稀疏矩陣的乘法
LeetCode刷題實戰(zhàn)312:戳氣球
LeetCode刷題實戰(zhàn)313:超級丑數
LeetCode刷題實戰(zhàn)314:二叉樹的豎直遍歷
LeetCode刷題實戰(zhàn)315:計算右側小于當前元素的個數
LeetCode刷題實戰(zhàn)316:去除重復字母
總結
以上是生活随笔為你收集整理的LeetCode刷题实战317:离建筑物最近的距离的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 测试111111111
- 下一篇: 华三交换机ping不通用户但用户_h3c