原题链接在这里: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 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. 317. Shortest Distance from All Buildings

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

  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] 821. Shortest Distance to a Character_Easy tag: BFS

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

  6. 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 613. Shortest Distance in a Line

    Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. Writ ...

  8. LeetCode 821 Shortest Distance to a Character 解题报告

    题目要求 Given a string S and a character C, return an array of integers representing the shortest dista ...

  9. [LeetCode] 613. Shortest Distance in a Line_Easy tag: SQL

    Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. Writ ...

随机推荐

  1. (三)shiro的认证

    文章目录 认证思路 自定义用于登录检验的Realm的思路 代码实现 后记 认证思路 调用 SecurityUtils.getSubject() 方法,获取当前的 Subject 对象 : 调用 Sub ...

  2. 剑指offer66:机器人的运动范围

    1 题目描述 地上有一个m行和n列的方格.一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子. 例如,当k为18时,机器 ...

  3. python基础 — 链接 Mysql 创建 数据库和创表

    重点: 1. 链接服务器的数据库 2. 创建表和格式 3. 插入多行数据 import pymysql try: host='xxx' user='xxx' passwd='xxx' db='test ...

  4. BC26模组UDP调试

    BC26模组调试 数据上报AT流程 [15:33:46.819]收←◆ F1: 0000 0000 V0: 0000 0000 [0001] 00: 0006 000C 01: 0000 0000 U ...

  5. STL中的函数对象实现负数的定义

    // // main.cpp // STL中的函数对象 // // Created by mac on 2019/5/2. // Copyright © 2019年 mac. All rights r ...

  6. cf 869c The Intriguing Obsession

    题意:有三种三色的岛,用a,b,c来标识这三种岛.然后规定,同种颜色的岛不能相连,而且同种颜色的岛不能和同一个其他颜色的岛相连.问有多少种建桥的方法. 题解:em....dp.我们先看两个岛之间怎么个 ...

  7. core直接获取报异常数据

    报异常直接跳转到/Home/Error [ResponseCache(Duration = , Location = ResponseCacheLocation.None, NoStore = tru ...

  8. c#基础知识梳理(一)

    一.C#简介 C#是微软公司发布的一种面向对象的.运行于.NET Framework之上的高级程序设计语言.C#看起来与Java有着惊人的相似:它包括了诸如单一继承.接口.与Java几乎同样的语法和编 ...

  9. 如何理解H264 编码

    H264 结构 https://blog.csdn.net/andywang201001/article/details/80274886 H264 源码  https://www.cnblogs.c ...

  10. 2019最新Web前端经典面试试题(含答案)

    1,阐述清楚浮动的几种方式(常见问题)(1)父级div定义 height原理:父级div手动定义height,就解决了父级div无法自动获取到高度的问题. 优点:简单.代码少.容易掌握 缺点:只适合高 ...