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的更多相关文章

  1. [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 ...

  2. 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的值. 最 ...

  3. [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 ...

  4. [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 ...

  5. LeetCode Shortest Distance from All Buildings

    原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...

  6. 317. Shortest Distance from All Buildings

    题目: Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where th ...

  7. [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 ...

  8. [LeetCode] Shortest Distance from All Buildings Solution

    之前听朋友说LeetCode出了一道新题,但是一直在TLE,我就找时间做了一下.这题是一个比较典型的BFS的题目,自己匆忙写了一个答案,没有考虑优化的问题,应该是有更好的解法的. 原题如下: You ...

  9. LeetCode 317. Shortest Distance from All Buildings

    原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...

随机推荐

  1. WebService如何封装XML请求 以及解析接口返回的XML

    原 WebService如何封装XML请求 以及解析接口返回的XML 置顶 2019年08月16日 15:00:47 童子泛舟 阅读数 28 标签: XML解析WebService第三方API 更多 ...

  2. HDU6223 Infinite Fraction Path bfs+剪枝

    Infinite Fraction Path 这个题第一次看见的时候,题意没搞懂就没做,这第二次也不会呀.. 题意:第i个城市到第(i*i+1)%n个城市,每个城市有个权值,从一个城市出发走N个城市, ...

  3. Solr6.0创建新的core

    现在solrhome文件夹下创建一个[new1_core]的文件夹,提示需要啥xml或者是txt就从下载好的solr6.0中去找,然后拷贝过来就行 这样的话,一般到最后会报 Error loading ...

  4. javascript面向对象 用new创建一个基于原型的javascript对象

    //创建一个类 其实就是个对象 var Student={ name:"robot", height:1.6, run:function(){ console.log(this.n ...

  5. Flask-配置参数

    Flask配置 Flask 是一个非常灵活且短小精干的web框架 , 那么灵活性从什么地方体现呢? 有一个神奇的东西叫 Flask配置 , 这个东西怎么用呢? 它能给我们带来怎么样的方便呢? 首先展示 ...

  6. codeforces#1187E. Tree Painting(树换根)

    题目链接: http://codeforces.com/contest/1187/problem/E 题意: 给出一颗树,找到一个根节点,使所有节点的子节点数之和最大 数据范围: $2 \le n \ ...

  7. 利用Python脚本完成一个Fat-tree型的拓扑

    利用Python脚本完成如下图所示的一个Fat-tree型的拓扑(交换机和主机名需与图中一致,即s1~s6,h1~h8) 参考资料 修改代码如下: from mininet.topo import T ...

  8. mysql 5.7.16 安装配置

    环境变量在path中添加一个 E:\soft\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin 查看mysql版本mysql -V 生成无密码账户进入到mysql ...

  9. shell 从键盘读取输入时删除输入的字符

    [参考文章]:stty命令的用法全解 [参考文章]:shell——read时退格异常(shell修改删除符) stty srase ^h read  -p  "请输入参数信息" 在 ...

  10. Imagetragick 命令执行漏洞(CVE-2016–3714)

    Imagetragick介绍: ImageMagick是一款使用量很广的图片处理程序,很多厂商都调用了这个程序进行图片处理,包括图片的伸缩.切割.水印.格式转换等等.但近来有研究者发现,当用户传入一个 ...