题目:

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.

Example:

Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]

1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0 Output: 7 Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2),
t
he 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.

 

链接: http://leetcode.com/problems/maximum-product-of-word-lengths/

题解:

给一块空地,求在空地上新盖一座楼,到其他楼的距离最短。这里我们要用到BFS,就是从每个楼开始用BFS计算空地 "0"到这栋楼的距离,最后把每个空地到每栋楼的距离加起来,求一个最小值。这里我们还要算出楼的数目,仅当空地能连接所有楼的时候,我们才愿意在这块空地上造楼。我们也要维护一个visited矩阵来避免重复。

Time Complexity - O(4mn), Space Complexity - O(mn * k), k为1的数目

public class Solution {
private final int[][] directions = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0) {
return Integer.MAX_VALUE;
}
int rowNum = grid.length;
int colNum = grid[0].length;
int[][] distance = new int[rowNum][colNum];
int[][] canReachBuildings = new int[rowNum][colNum];
int buildingNum = 0; for(int i = 0; i < rowNum; i++) {
for(int j = 0; j < colNum; j++) {
if(grid[i][j] != 0) {
distance[i][j] = Integer.MAX_VALUE;
}
if(grid[i][j] == 1) { // find out all buildings
buildingNum++;
updateDistance(grid, distance, canReachBuildings, i, j);
}
}
} int min = Integer.MAX_VALUE;
for(int i = 0; i < rowNum; i++) {
for(int j = 0; j < colNum; j++) {
if(canReachBuildings[i][j] == buildingNum) {
min = Math.min(distance[i][j], min);
}
}
} return min == Integer.MAX_VALUE ? -1 : min;
} private void updateDistance(int[][] grid, int[][] distance, int[][] canReachBuildings, int row, int col) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{row, col});
boolean[][] visited = new boolean[grid.length][grid[0].length];
visited[row][col] = true;
int dist = 0;
int curLevel = 1;
int nextLevel = 0; while(!queue.isEmpty()) {
int[] position = queue.poll();
distance[position[0]][position[1]] += dist;
curLevel--;
for(int[] direction : directions) {
int x = position[0] + direction[0];
int y = position[1] + direction[1];
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] != 0) {
continue;
}
if(!visited[x][y]) {
queue.offer(new int[]{x, y});
nextLevel++;
visited[x][y] = true;
canReachBuildings[x][y]++;
}
}
if(curLevel == 0) {
curLevel = nextLevel;
nextLevel = 0;
dist++;
}
}
}
}

Reference:

https://leetcode.com/discuss/74453/36-ms-c-solution

https://leetcode.com/discuss/74422/clean-solution-easy-understanding-with-simple-explanation

https://leetcode.com/discuss/74999/java-solution-with-explanation-and-time-complexity-analysis

https://leetcode.com/discuss/74380/my-bfs-java-solution

317. Shortest Distance from All Buildings的更多相关文章

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

  2. LeetCode 317. Shortest Distance from All Buildings

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

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

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

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

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

  7. LeetCode Shortest Distance from All Buildings

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

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

  9. [LeetCode] Shortest Distance from All Buildings Solution

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

随机推荐

  1. EF之外键Include() left join

    项目中用EF实现外键查询出的数据, 查询数量正确, 但实现返回数据集数量不对 //DbContext.cs HasRequired(s => s.ClassRoom) .WithMany() . ...

  2. gameObject, vector and transform

    调用其它组件中成员 通过GameObject(游戏物体). Base class for all entities in Unity scenes.  是Unity场景里面所有实体的基类. 可以理解为 ...

  3. 本人在安装ADT Bundle for windows的各种问题总结

    本人在安装ADT Bundle for windows的各种问题总结 1.解决国内访问Google服务器的困难: 1.启动 Android SDK Manager : 2.打开主界面,依次选择「Too ...

  4. 我是一只it小小鸟阅读笔记

    “我们具有各自的独特性--我们兴趣各异,有不同的家庭背景,不同的知识储备,不同的思维方式……但在现实中,我们也会碰到类似的人生选择的关口,我们会犯类似的错误,有类似的迷惘,也会为类似的精彩鼓掌,而且很 ...

  5. 【BZOJ】【2565】最长双回文串

    Manacher算法 找出一个最长子串S=X+Y,且X和Y都是回文串,求最长的长度是多少…… 同时找两个串明显很难搞啊……但是我们可以先找到所有的回文串!在找回文串的同时我们可以预处理出来l[i]和r ...

  6. [bzoj 2097]奶牛健美操

    题目描述 对于一棵n个点的树,删除k条边,使得所有联通块直径最大值最小 题解 首先二分联通块直径最大值的最小值. 那么这个能否达成的判定变成了一个类似树形dp的东西 对于一个子树,删除一条边可以删除整 ...

  7. redis提示Could not get a resource from the pool(jedis连接池配置)

    起初在JedisPool中配置了50个活动连接,但是程序还是经常报错:Could not get a resource from the pool 连接池刚开始是这样配置的: JedisPoolCon ...

  8. Feature Engineering versus Feature Extraction: Game On!

    Feature Engineering versus Feature Extraction: Game On! "Feature engineering" is a fancy t ...

  9. [百度空间] [转] 四元数(Quaternions)

    转:四元数(Quaternions) 好吧,我必须承认到目前为止我还没有完全理解四元数,我一度把四元数理解为轴.角表示的4维向量,也就在下午我才从和同事的争辩中理解了四元数不完全是角.轴这么简单,为此 ...

  10. 为什么主流网站无法捕获 XSS 漏洞?

    二十多年来,跨站脚本(简称 XSS)漏洞一直是主流网站的心头之痛.为什么过了这么久,这些网站还是对此类漏洞束手无策呢? 对于最近 eBay 网站曝出的跨站脚本漏洞,你有什么想法?为什么会出现这样的漏网 ...