[Leetcode] 317. Shortest Distance from All Buildings 解题报告

317 离建筑物最近的距离 题目描述: 你是个房地产开发商,想要选择一片空地 建一栋大楼。你想把这栋大楼够造在一个距离周边设施都比较方便的地方,通过调研,你希望从它出发能在 最短的距离和 内抵达周边全部的建筑物。请你计算出这个最佳的选址到周边全部建筑物的 最短距离和。 提示: 你只能通过向上、下、左、右四个方向上移动。 给你一个由 0、1 和 2 组成的二维网格,其中: 0 代表你可以自由通过和选择建造的空地 1 代表你无法通行的建筑物 2 代表你无法通行的障碍物 示例: 输入:[[1,0,2,0,1],[0,0,0,0,0],[0, 阅读详情

题目:

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,我们在grid上利用BFS来获取所有空白处到该建筑的距离;当所有building的结果都计算出来之后,对应位置加起来,最小值即为最优选择。朴素的代码可能需要另外开辟存储空间以及访问标记。

在下面的实现中,我们巧妙利用了grid中空白处的值0。也就是说,在对第一个建筑物求BFS的时候,我们只遍历grid[x][y] == 0的地方,一旦遍历之后,就将其值置为-1;在对第二个建筑物求BFS的时候,我们只遍历grid[x][y] == -1的地方,并且在遍历之后,就将其值置为-2,以此类推,直到所有的建筑物都被遍历。

代码:

class Solution {
public:
    int shortestDistance(vector<vector<int>>& grid) {
        if(grid.size() == 0) {
            return 0;
        }
        int row_num = grid.size(), col_num = grid[0].size();
        int ret = 0, flag = 0;
        vector<pair<int, int>> dir{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        vector<vector<int>> count(row_num, vector<int>(col_num, 0));
        for(int i = 0; i < row_num; ++i) {
            for(int j = 0; j < col_num; ++j) {
                if(grid[i][j] != 1) {
                    continue;
                }
                ret = INT_MAX;  // It is a bit tricky to understand why here we define ret and intiailize it as INT_MAX
                                // Each time it is first initialized as INT_MAX, and then updated as minimal summed distances
                queue<pair<int, int>> que;
                que.push(make_pair(i * col_num + j, 0));    // map 2D matrix to 1D array
                while(!que.empty()) {
                    auto val = que.front();
                    que.pop();
                    for(auto v : dir) {
                        int x = val.first / col_num + v.first;
                        int y = val.first % col_num + v.second;
                        if(x < 0 || x >= row_num || y < 0 || y >= col_num || grid[x][y] != flag) {
                            continue;
                        }
                        count[x][y] += val.second + 1;
                        --grid[x][y];
                        ret = min(ret, count[x][y]);
                        que.push(make_pair(x * col_num + y, val.second + 1));
                    }
                }
                --flag;
            }
        }
        return ret == INT_MAX ? -1 : ret;
    }
};
[leetcode] 317. Shortest Distance from All Buildings 解题报告 题目链接: https://leetcode.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 m 阅读详情

相关推荐

leetcode296-leetcode:我的力扣解决方案

第 296 章leetcode 我的力扣解决方案 # 标题 解决方案 困难 324 Java 中等的 323 Java 中等的 322 Java 中等的 321 Java 中等的 320 Java 中等的 319 Java 中等的 318 Java 中等的 317 Java 中等的 316 Java 中等的 315 Java 中等的 314 Java 中等的 313 Java 中等的 312 Java 中等的 311 Java 中等的 310 Java 中等的 309 Java 中等的 308 Java 中等的 307 Java 中等的 306 Java 中等的 305 Java 中等的 304 Java 中等的 303 Java 中等的 302 Java 中等的 301 Java 中等的 300 Java 中等的 299 Java 中等的 298 Java 中等的 297 Java 中等的 296 Java 中等的 295 Java 中等的 294 Java 中等的 293 Java 中等的 292 Java 中等的 291 Java 中等的 290 Java 中等的 289 Jav

leetcode:317. 离建筑物最近的距离

【代码】leetcode:317. 离建筑物最近的距离。

OceanStar的博客 531

三菱FX5U PLC与CCLINK模块通信配置全流程(附接线图与参数详解)

本文详细解析了三菱FX5U PLC与CCLINK模块的通信配置全流程,包括硬件接线规范、参数设置及软件编程方法。通过实战指南帮助工程师快速掌握FX5U与CCLINK模块的高效通信技术,提升工业自动化控制系统的稳定性和可靠性。

weixin_27014595的博客 427

LeetCode 317. 离建筑物最近的距离(逆向BFS)*

文章目录1. 题目2. 解题2.1 正常思维BFS2.2 逆向思考BFS 1. 题目 你是个房地产开发商,想要选择一片空地 建一栋大楼。 你想把这栋大楼够造在一个距离周边设施都比较方便的地方,通过调研,你希望从它出发能在 最短的距离和 内抵达周边全部的建筑物。 请你计算出这个最佳的选址到周边全部建筑物的 最短距离和。 提示: 你只能通过向上、下、左、右四个方向上移动。 给你一个由 0、1 和 2 组成的二维网格,其中: 0 代表你可以自由通过和选择建造的空地 1 代表你无法通行的建筑物 2 代表你无法通行

Michael是个半路程序员 6492

STM32CUBEMX+STM32H750VB+LWIP+LAN8720A+FREERTOS TCP服务器、UDP数据接收发送、网线热插拔、IAR-8.32开发

STM32CUBEMX+STM32H750VB+LWIP+LAN8720A+FREERTOS TCP服务器、UDP数据接收发送、网线热插拔、IAR-8.32开发STM32H750VB使用STM32CUBEMX生成工程IAR+J-LINK调试准备工作CUBEMX生成的代码问题所在如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章U

qq_37433166的博客 5343

不会写GLSL?用Cesium 1.120 + Heatmap.js 2.0.5也能搞定动态洪水模拟(附完整源码)

本文介绍了一种无需GLSL编程的3D洪水动态模拟方案,结合Cesium 1.120和Heatmap.js 2.0.5实现高效可视化。通过数据层、可视化层和集成层的技术降级方案,开发者可以快速构建专业级洪水演进效果,适用于应急管理、水利工程等场景。文章包含完整源码和性能优化技巧。

weixin_30329623的博客 520

力扣 317 离建筑物最近的距离 BFS

力扣 317 离建筑物最近的距离 BFS

yu_duan_hun的博客 1116

软考高级信息系统项目管理师系列论文之:百篇软考高级信息系统项目管理师论文范文

软考高级信息系统项目管理师系列论文之:百篇软考高级信息系统项目管理师论文范文

zhengzaifeidelushang的博客 3578

leetcode 317. 离建筑物最近的距离

广度优先搜索,记录=1的格子,以及1的数量,然后产生一个3D的矩阵,保存distance,1d,2d和grid相同,3d用来放置每个=1的格子到这的distance;对每个1都做了标号,按照标号填充3D矩阵; 从所有的1开始,每次step 1步,然后加入队列的,并算distance和保存。 最后循环每个格子,若是3d方向最小值=0,说明某个1不能到达这里,不求最小值跳过;然后求3d方向的累加值并求最小值。 若最小值没有update,说明所有的空地0都有某些1不能到达不满足条件-1; 作者:九是否随意的称呼

邹九的个人博客 750

6.3 节深度拆解:Hermes Agent 多 Agent 协同执行链路的 4 层设计逻辑

拆解 Hermes 多 Agent 协同的 4 层工程化设计(协议层、编排层、执行层、适配层),聚焦协议层的强约束消息 Schema 如何解决 Agent 间语义不一致问题,并提供 `soul.md` 配置、GLM-4.7Flash 结构化输出验证及 v0.13.0/v0.14.0 版本实操避坑指南

weixin_42520239的博客 122

canoe安装完成开启之后因为VectorDeviceParams30_64.dll报错崩溃打不开...如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值。

**My Coding Family** 1074

[Leetcode] 317. Shortest Distance from All Buildings

这题算是https://blog.csdn.net/chaochen1407/article/details/82720327的延伸。相当于那一题加了两个限定条件:1. 1本身不能成为聚集点。2.多了2这个数字代表obstacle。 加了这两个限定条件,就没办法采取那道题目的最优解决法了。目前所知的最优解就是遍历bfs。就是以每个building为起始点,然后往外bfs,对每个能达到的点进...

chaochen1407的专栏 524

人体分割笔记总结

人体分割 人体分割(human parsing),属于语义分割任务的子任务,旨在对人类图像进行像素级的是细粒度分割(例如,划分出身体部位和服装)。根据不同的场景,又可以分为单人人体解析(single-person human parsing)和多人人体解析(multi-person human parsing,或者 instance-level human parsing)。除此之外,按照处理媒介分类,还可以分为基于图像的人体解析和基于视频的人体解析。 对于人体解析任务,常用的度量指标包括 Pixel a

jacke121的专栏 4255

Leetcode 317. Shortest Distance from All Buildings (python+cpp)

Leetcode 317. Shortest Distance from All Buildings题目解法1:BFS解法2: 题目 解法1:BFS brutal force的从每一个空地出发,找与building的最短距离之和 class Solution: def shortestDistance(self, grid: List[List[int]]) -> int: def helper(i,j): visited = set()

qq_37821701的博客 1779

ARM与PC共享文件方式【samba】移植与配置

方式推荐指数适用平台优点缺点⭐⭐⭐⭐⭐全平台 (Win/Mac/Linux)兼容性最强,操作像本地文件配置稍繁琐,协议开销略大NFS⭐⭐⭐⭐Linux/Mac (Win支持一般)速度极快,CPU占用低Windows配置复杂,权限管理较难SFTP (SSH)⭐⭐⭐⭐全平台 (需客户端)安全加密,无需额外配置服务需使用FileZilla/Xftp等专用软件物理U盘⭐⭐⭐全平台无需网络,速度取决于接口需要人工插拔,不适合自动化Syncthing⭐⭐⭐⭐全平台自动同步,支持远程。

浩瀚之水的专栏 263

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

[LeetCode317]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 are given a 2D grid of values 0, 1 or 2, where:Each 0 marks an empty land which you can pa

MoM 2592

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

LeetCode 317. Shortest Distance from All Buildings(最短建筑距离)

原题网址:https://leetcode.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

James Pan 3655

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

317. Shortest Distance from All Buildings

317. Shortest Distance from All Buildings方法0: bfs,TLE方法2: bfs 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, lef...

wilzxu的博客 370

Leetcode 317. Shortest Distance from All Buildings

#include #include #include #include using namespace std; /* 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

ActiveCoder的博客 966

LeetCode #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 ...

LawFile的博客 174

LeetCode317 Shortest Distance from All Buildings

...

李歇特冯-兹拜因巴哈的博客 407

【Leetcode】317. Shortest Distance from All Buildings

题目地址: https://leetcode.com/problems/shortest-distance-from-all-buildings/ 给定一个二维矩阵,只含0,1,20,1,20,1,2,000代表空地,111代表建筑,222代表障碍物。要求在一个空地建个房屋,使得房屋到所有建筑物的路径长度之和达到最小。路径的每一步只能向上下左右走,并且只能走到空地上。如果存在房屋的建造方案,则返回最短路径长度总和;否则返回−1-1−1。 思路是BFS。可以从每个建筑物出发,遍历一下其所能到达的空地,并累加该

数学、算法爱好者的博客 842

[Swift]LeetCode317. 建筑物的最短距离 $ Shortest Distance from All Buildings

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30263073的博客 555

leetcode 317 shortest distance from all buildings

1 0 2 0 1 0 0 0 0 0 0 0 1 0 0 第一个building, 把涂色把0变成-1, 同一层最终会涂成相同颜色-1 1 -1 2 -1 1 -1 -1 -1 -1 -1 -1 -1 1 -1 ...

weixin_33872660的博客 209

Leetcode 317. Shortest Distance from All Buildings(多次BFS)

Leetcode 317. Shortest Distance from All Buildings

快乐的小鸟_ZJU 583
上一篇: [Leetcode] 316. Remove Duplicate Letters 解题报告
下一篇: [Leetcode] 318. Maximum Product of Word Lengths 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值