题目:

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. tcp传输黏包

    tcp传输黏包 tcpip协议使用"流式"(套接字)进行数据的传输,就是说它保证数据的可达以及数据抵达的顺序,但并不保证数据是否在你接收的时候就到达,特别是为了提高效率,充分利用带 ...

  2. ASCII码排序

    ASCII码排序 时间限制:3000 ms  |  内存限制:65535 KB 难度:2   描述 输入三个字符(可以重复)后,按各字符的ASCII码从小到大的顺序输出这三个字符.   输入 第一行输 ...

  3. nodejs笔记四--创建一个最简单的 express 应用

    express 是 Node.js 应用最广泛的 web 框架,利用 express 可以实现很多的web应用:首先需要需要得到一个express. 新建一个文件夹叫lesson1,进去里面安装 ex ...

  4. 多种方法实现H5网页图片动画效果;

    在web开发中,GIF动画效果是随处可见,比如常见的loading加载.人物奔跑的gif图片等等,那么这些都是怎么实现的呢?其实实现的原理很简单,简而言之,这些所谓的动画都是一帧一帧的图片经过一段时间 ...

  5. C#开源大全--汇总(转)

    商业协作和项目管理平台-TeamLab 网络视频会议软件-VMukti 驰骋工作流程引擎-ccflow [免费]正则表达式测试工具-Regex-Tester Windows-Phone-7-SDK E ...

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

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

  7. Promises与Javascript异步编程

    Promises与Javascript异步编程 转载:http://www.zawaliang.com/2013/08/399.html 在如今都追求用户体验的时代,Ajax应用真的是无所不在.加上这 ...

  8. Python爬取百度贴吧图片

    一.获取URL Urllib 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据.首先,我们定义了一个getHtml()函数: urllib.urlopen()方 ...

  9. IIS Express 一个网站配置多个 域名

      在配置localhost和IP都可以访问:   方法1: applicationhost.config文件配置: <bindings>   <binding protocol=& ...

  10. Unity3d之音效播放和调用手机震动

    http://blog.csdn.net/sunshine_1984/article/details/12943979 今天研究了下Unity3d音效播放相关内容,整理下实现细节. 1,添加音效文件到 ...