题目:

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. VC++ MFC 如何实现在编辑框中输出具有换行功能的文段 01

    很久不来写东西了,昨天睡觉前写个小工具,突然,这玩意不会换行怎么整... 首先是第一步,获取字符串的长度,转载自白乔的文章. ------------------------------------- ...

  2. Redis基础教程

    说明:本文中涉及的代码是c#所写,连接redis的第三方驱动为ServiceStack.Redis.连接redis的客户端软件为redis-desktop-manager. 一.Redis是什么 Re ...

  3. 升级ubuntu内核

    ubuntu12.04内核为 linux-image-3.5.0-23-generic 要升级为 linux-image-3.2.0-57-generic 使用apt-get install linu ...

  4. Struts2中的ModelDriven机制及其运用(转)

    所谓ModelDriven,意思是直接把实体类当成页面数据的收集对象.比如,有实体类User如下: package cn.com.leadfar.struts2.actions; public cla ...

  5. Visual Studio 2013

    1.How to hide reference counts in VS2013? Tools--> Options --> Text Editor --> All Language ...

  6. hdu 3879 Base Station 最大权闭合图

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3879 A famous mobile communication company is plannin ...

  7. hdu 3068 最长回文 manacher

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3068 给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.回文就是正 ...

  8. 【BZOJ】【1040】【ZJOI2008】骑士

    树形DP/基环树DP 我掉坑掉了好多…… 这题图比较特殊,每个连通块都是一棵基环树(我一开始以为图是连通的了……sigh,我说为什么网上的题解都要累加ans……),那么对于一棵基环树,我们先dfs找到 ...

  9. HTTP1.1缓存策略

    以下是一幅虽然信息包含量有限.但足够以最简洁的方式说明了“什么是HTTP1.1缓存策略”的图  缓存和缓存策略 web缓存(web cache)或代理缓存(proxy cache)是一种特殊的HTTP ...

  10. word插件开发 运行时,插件不启动.

      word插件开发 运行时,插件不启动. 查看插件信息时. 在禁用的应用程序加载项中.   启动禁用的插件: 点击转到.  选择你要启动的插件就可以了.