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 ...
随机推荐
- 【luoguUVA1316】 Supermarket--普通并查集+贪心
题目描述 有一个商店有许多批货,每一批货又有N(0<=N<=10^4 )个商品,同时每一样商品都有收益P_iPi ,和过期时间D_iDi (1<=Pi,,Di <=10^4 ...
- 【线性代数】3-1:向量空间(Space of Vectors)
title: [线性代数]3-1:向量空间(Space of Vectors) categories: Mathematic Linear Algebra keywords: Vectors Spac ...
- Linux的简单命令(防火墙篇)
名称 解释 重启 reboot 关机 shutdown -h now poweroff 查看本机IP地址 ifconfig 查看默认网卡信息的文件 cat /etc/sysconfig/netw ...
- Kafka Eagle 安装
Kafka Eagle 是一款开源的 Kafka 集群监控系统. 一.下载 https://download.kafka-eagle.org/ 二.安装 # 解压 .tar.gz -C /opt/ / ...
- java读取XML文件,及封装XML字符串
package com.yyl.text; import java.io.FileInputStream; import java.util.ArrayList; import org.junit.T ...
- ios wkwebview allowFileAccessFromFileURLs
最近在做 cordova 打包 ios 的项目(webpack 打包 vue项目后,再用 cordova 打包).在加载 file:/// 协议时因为 webview安全机制有一些报错.SK各种找解决 ...
- linux安装jdk1.8之后报错Error: dl failure on line 893的解决办法
问题描述:安装jdk1.8之后,输入java -version查看安装是否成功之后,报错: 报错如下: Error: dl failure on line 893 Error: failed /u ...
- shell 脚本基础与条件判断
#!shell脚本格式决定专业性 #!/bin/bash #filename:脚本名 #author:作者 #date:时间 #脚本作用 脚本的执行方式 #脚本名为wk.sh 绝对路径 /root/ ...
- Handler注意事项
一. Handler与Thread的区别. Handler与调用者处于同一线程,如果Handler里面做耗时的动作,调用者线程会阻塞.Android UI操作不是线程安全的,并且这些操作必须在UI线程 ...
- 利用Spring的AbstractRoutingDataSource解决多数据源的问题【代码手动切换,非AOP】
转: 利用Spring的AbstractRoutingDataSource解决多数据源的问题 多数据源问题很常见,例如读写分离数据库配置. 原来的项目出现了新需求,局方要求新增某服务器用以提供某代码, ...