原题链接在这里: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. MYSQL 八大优化方案

    1.选取最适用的字段属性 ​ MySQL可以很好的支持大数据量的存取,但是一般说来,数据库中的表越小,在它上面执行的查询也就会越快.因此,在创建表的时候,为了获得更好的性能,我们可以将表中字段的宽度设 ...

  2. logback日志无法按日期分割的问题

    发现在线上的时候,日志无法按日期分割的问题,所有日志都在第一天部署的那个日期的文件里面. 背景是Springboot + logback 原因是: 之前是: 用timeBaseRollingPolic ...

  3. Oracle触发器编译错误及解决方案

    错误 TRIGGER **** 编译错误 错误:PLS-00103: 出现符号 "END"在需要下列之一时:        ( begin case declare exit    ...

  4. MongoDB安装及环境配置

    一.什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为WEB应用提供 ...

  5. Detection综述

    4月中旬开始,尝试对目标检测领域做一个了解,看了差不多6-7篇paper,在这里记录一下: 一.Detection简介 人脸检测的目标是找出图像中所有的人脸对应的位置,算法的输出是人脸外接矩形在图像中 ...

  6. Django2.0 分页的应用

    #分页例子from django.core.paginator import Paginatordef blog_list(request):      blog_all_list = models. ...

  7. Java源码阅读之ArrayList

    基于jdk1.8的ArrayList源码分析. 实现List接口最常见的大概就四种,ArrayList, LinkedList, Vector, Stack实现,今天就着重看一下ArrayList的源 ...

  8. navigator(浏览器对象)Screen对象(屏幕)

    浅谈navigator对象: 注意:不是所有浏览器都支持 .cookieEnabled  判断是否启用了cookie  在客户端硬盘持久保存用户私密数据的小文件 .plugins 浏览器安装的所有插件 ...

  9. git推送代码Gogs报401错误

    1.git push 报错:RPC failed; HTTP 401 curl 22 The requested URL returned error: 401 The remote end hung ...

  10. Thymeleaf 模板

    Thymeleaf 模板布局 th:fragment.th:replace.th:insert.th:remove th:fragment  模板布局 模板片段说明 模板中,经常希望从其他模板中包含⼀ ...