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.
思路:
从每个点是1的点出发,通过bfs找到这个点到每个0点最短距离,同时记录该0点被1点访问过的次数。这样我们遍历所有1点,对所有能够被访问到的1点,保存最短距离以及增加访问次数。最后把所有0点遍历一遍,看它是否被所有1点访问到,并且最短距离和最小。
其实这里也可以从0出发,做类似的事情。选1还是0看它们的个数。谁小就选谁。
public class Solution {
private int[][] dir = { { -, }, { , }, { , - }, { , } }; public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == ) {
return ;
} int rows = grid.length, cols = grid[].length, numBuildings = ;
int[][] reach = new int[rows][cols], distance = new int[rows][cols]; // Find the minimum distance from all buildings
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == ) {
shortestDistanceHelper(i, j, grid, reach, distance);
numBuildings++;
}
}
} // step 2: check the min distance reachable by all buildings
int minDistance = Integer.MAX_VALUE;
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == && reach[i][j] == numBuildings && distance[i][j] < minDistance) {
minDistance = distance[i][j];
}
}
}
return minDistance == Integer.MAX_VALUE ? - : minDistance;
} private void shortestDistanceHelper(int row, int col, int[][] grid, int[][] reach, int[][] distance) {
int rows = grid.length, cols = grid[].length, d = ;
boolean[][] visited = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] { row, col });
visited[row][col] = true;
while (!queue.isEmpty()) {
d++;
int size = queue.size();
for (int j = ; j < size; j++) {
int[] cord = queue.poll();
for (int i = ; i < ; i++) {
int rr = dir[i][] + cord[];
int cc = dir[i][] + cord[];
if (isValid(rr, cc, grid, visited)) {
queue.offer(new int[] { rr, cc });
visited[rr][cc] = true;
reach[rr][cc]++;
distance[rr][cc] += d;
}
}
}
}
} private boolean isValid(int row, int col, int[][] grid, boolean[][] visited) {
int rows = grid.length, cols = grid[].length;
if (row < || row >= rows || col < || col >= cols || visited[row][col] || grid[row][col] == ) {
return false;
}
return true;
}
}
Shortest Distance from All Buildings的更多相关文章
- [Locked] Shortest Distance from All Buildings
Shortest Distance from All Buildings You want to build a house on an empty land which reaches all bu ...
- leetcode 542. 01 Matrix 、663. Walls and Gates(lintcode) 、773. Sliding Puzzle 、803. Shortest Distance from All Buildings
542. 01 Matrix https://www.cnblogs.com/grandyang/p/6602288.html 将所有的1置为INT_MAX,然后用所有的0去更新原本位置为1的值. 最 ...
- [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 dis ...
- [LeetCode] Shortest Distance from All Buildings 建筑物的最短距离
You want to build a house on an empty land which reaches all buildings in the shortest amount of dis ...
- LeetCode Shortest Distance from All Buildings
原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...
- 317. Shortest Distance from All Buildings
题目: Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where th ...
- [Swift]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 dis ...
- [LeetCode] Shortest Distance from All Buildings Solution
之前听朋友说LeetCode出了一道新题,但是一直在TLE,我就找时间做了一下.这题是一个比较典型的BFS的题目,自己匆忙写了一个答案,没有考虑优化的问题,应该是有更好的解法的. 原题如下: You ...
- LeetCode 317. Shortest Distance from All Buildings
原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...
随机推荐
- nginx大概工作机制
1.master和worker nginx启动后,会有2种进程:worker和master;worker可能有多个:
- shell 脚本拉取svn代码,vim中文乱码解决办法
VIM安装成功后可以使用,但对中文是乱码,解决方法是在vim的配置文档中添加相关设置即可: 找到etc/vimrc 编辑~/.vimrc文件,加上如下几行: set fileencodings=utf ...
- POJ 1236 Network of Schools —— (缩点的应用)
题目大意:有N个学校和一些有向边将它们连结,求: 1.最少需要向几个学校发放软件,使得他们中的每一个学校最终都能够获得软件. 2.最少需要增加几条有向边使得可以从任意一个学校发放软件,使得每一个学校最 ...
- spark 常用函数介绍(python)
以下是个人理解,一切以官网文档为准. http://spark.apache.org/docs/latest/api/python/pyspark.html 在开始之前,我先介绍一下,RDD是什么? ...
- HearthBuddy遇奥秘解决方法
https://tieba.baidu.com/g/5808796816 链接: https://pan.baidu.com/s/1NPQTOfxbN_4alP7J-XWuVw 密码: xfj1
- Java-LockSupport
LockSupport 和 CAS 是 Java 并发包中很多并发工具控制机制的基础,它们底层其实都是依赖 Unsafe 实现. LockSupport 提供 park() 和 unpark() 方法 ...
- win10下EditPlus不能拖拽打开文件
今天找到篇blog,终于把win10下EditPlus不能拖拽打开文件的问题解决了:) 记录下备忘.之前通过注册表的方式添加到右键菜单,当时设置了EditPlus以管理员身份运行: 解决办法=> ...
- piggy back是什么意思?
遇到这么一句话. // Connect the Socket.IO framework up to the web server to piggy back on its connection // ...
- CentOS 7系统配置上的变化
http://www.linuxidc.com/Linux/2014-09/107375p4.htm CentOS 7系统配置上的变化解析 ip ss指令替代 ifconfig route arp n ...
- 微信小程序tabBar的一个小坑
开始接触微信小程序的项目开发时,自己想添加底部导航,按照文档的方法在app.json添加tabBar,结果编译不出,工具台也没错误提示. 尝试在网上搜一下,看到有碰到类似情况的,解决方法是:app.j ...