原题链接在这里:https://leetcode.com/problems/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.

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.

题解:

从每一座building开始做BFS, 更新每个空地达到building的距离总和 以及 每个空地能到达building的个数.

第二次扫描grid, 若是空地并且它能到达的building数目是总共的building数目,就更新min距离.

Note: For the second iteration, check 2 conditions. grid[i][j] < 0 && reachCount[i][j] = totalCount.

Time Complexity: O(m^2 * n^2), 每次BFS用O(mn), 一共做了m*n次BFS.

Space: O(m*n)

AC Java:

 class Solution {
public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0){
return 0;
} int m = grid.length;
int n = grid[0].length; //记录每个点能够到达building的个数
int [][] reachCount = new int[m][n];
int totalCount = 0; for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
if(grid[i][j] == 1){
//遇到building, 从这个building开始做bfs
totalCount++;
bfs(grid, i, j, reachCount);
}
}
} int res = Integer.MAX_VALUE;
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
if(grid[i][j] < 0 && reachCount[i][j] == totalCount){
res = Math.min(res, -grid[i][j]);
}
}
} return res == Integer.MAX_VALUE ? -1 : res;
} int [][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private void bfs(int [][] grid, int i, int j, int [][] reachCount){
int level = 0;
int m = grid.length;
int n = grid[0].length;
LinkedList<int []> que = new LinkedList<>();
boolean[][] visited = new boolean[m][n];
que.add(new int[]{i, j});
visited[i][j] = true; while(!que.isEmpty()){
int size = que.size();
while(size-- > 0){
int [] cur = que.poll();
grid[cur[0]][cur[1]] -= level;
reachCount[cur[0]][cur[1]]++; for(int [] dir : dirs){
int x = cur[0] + dir[0];
int y = cur[1] + dir[1];
if(x < 0 || x >=m || y < 0 || y >=n || visited[x][y] || grid[x][y] > 0){
continue;
} que.add(new int[]{x, y});
visited[x][y] = true;
}
} level++;
}
}
}

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

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

  2. [LeetCode] Shortest Distance from All Buildings Solution

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

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

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

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

  6. [LeetCode] Shortest Distance to a Character 到字符的最短距离

    Given a string S and a character C, return an array of integers representing the shortest distance f ...

  7. 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 317. Shortest Distance from All Buildings

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

  9. 317. Shortest Distance from All Buildings

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

随机推荐

  1. ccc tiledmap

    //移动方向枚举类 var MoveDirection = cc.Enum({ NONE: 0, UP: 1, DOWN: 2, LEFT: 3, RIGHT: 4 }); var minTilesC ...

  2. BZOJ3764 : Petya的序列

    首先如果一段连续子序列里没有任何幸运数,那么显然可以缩成一个点. 设幸运数个数为$m$,那么现在序列长度是$O(m)$的,考虑暴力枚举$R_1$,然后从右往左枚举$L_1$. 每次碰到一个幸运数,就将 ...

  3. HDU 2822 (BFS+优先队列)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2822 题目大意:X消耗0,.消耗1, 求起点到终点最短消耗 解题思路: 每层BFS的结点,优先级不同 ...

  4. 使用 google gson 转换Timestamp或Date类型为JSON字符串.

    http://blog.csdn.net/z69183787/article/details/13016289 创建类型适配类: import java.lang.reflect.Type; impo ...

  5. 微信客户端自带的Js Api:WeixinJSBridge

    <!DOCTYPE html> <html> <head> <title>微信WeixinJSBridge API</title> < ...

  6. Codeforces Round #243 (Div. 2) C. Sereja and Swaps

    由于n比较小,直接暴力解决 #include <iostream> #include <vector> #include <algorithm> #include ...

  7. 【BZOJ2821】作诗(Poetize) 分块

    Description 神犇SJY虐完HEOI之后给傻×LYD出了一题:SHY是T国的公主,平时的一大爱好是作诗.由于时间紧迫,SHY作完诗之后还要虐OI,于是SHY找来一篇长度为N的文章,阅读M次, ...

  8. Android -- TextView (3)

    1.效果图

  9. Android -- TextView、button方法详解(1)

    1.TextView常规方法 TextView myTextView=null; //声明变量 myTextView=(TextView)findViewById(R.id.myTextView); ...

  10. linux下tar命令详解

     linux下tar命令详解    tar是Linux环境下最常用的备份工具之一.tar(tap archive)原意为操作磁带文件,但基于Linux的文件操作机制,同样也可适用于普通的磁盘文件.ta ...