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 ...
随机推荐
- learning armbian steps(8) ----- armbian 源码分析(三)
在lib/main.sh当中 ) == main.sh ]]; then echo "Please use compile.sh to start the build process&quo ...
- 【洛谷2050】 [NOI2012]美食节(费用流)
大家可以先看这道题目再做! SCOI2007修车 传送门 洛谷 Solution 就和上面那道题目一样的套路,但是发现你会获得60~80分的好成绩!!! 考虑优化,因为是SPFA,所以每一次只会走最短 ...
- 【BZOJ3098】 Hash Killer II
BZOJ3098 Hash Killer II Solution 这道题目好像题面里面给了提示(当然没给就有点难想了.) 曾经讲过一个叫做生日悖论的,不知道还有多少人记得 考虑相同的可能性大概是\(\ ...
- Java终止线程的三种方式
停止一个线程通常意味着在线程处理任务完成之前停掉正在做的操作,也就是放弃当前的操作. 在 Java 中有以下 3 种方法可以终止正在运行的线程: 使用退出标志,使线程正常退出,也就是当 run() 方 ...
- Java实验报告(一)
Java实验报告(一) 实验过程 1. 打印输出所有的"水仙花数",所谓"水仙花数"是指一个3位数,其中各位数字立方和等于该数本身.例如,153是一个" ...
- SDN上机第4次作业
1. 解压安装OpenDayLight控制器(本次实验统一使用Beryllium版本) 1)JDK的安装与环境配置 嗯,装这个东西还得先装JDK: 在线真人手把手教你安装jdk 输入sud ...
- mysql:启动服务时遇到的问题
1.cmd命令: 在切换路径时,如果要切到另外一个磁盘,比如从C盘切到E盘,命令如下: cd /d 你要切换的路径 2.错误:“服务名无效” 问题原因:mysql服务没有安装.(参考:https:// ...
- react-native(ios)简单配置环境(mac)
1.首先全局安装react-native-cli npm install -g react-native-cli 2.安装xcode(appStore) 3.打开xcode,检查一下是否装有某个版本的 ...
- koa 实现下载文件
文件下载需要使用到koa-send这个插件,该插件是一个静态文件服务的中间件,它可以用来实现文件下载的功能. 1.下载页面 static/download.html <!DOCTYPE html ...
- 指定pip清华源
临时指定: pip install cefpython3 -i https://pypi.tuna.tsinghua.edu.cn/simple 一直使用:pip的配置文件为%HOME%/pip/pi ...