LeetCode 317. Shortest Distance from All Buildings
原题链接在这里: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),he point
t(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的更多相关文章
- [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 ...
- 317. Shortest Distance from All Buildings
题目: Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where th ...
- 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的值. 最 ...
- [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 ...
- [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 ...
- 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 ...
- 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 ...
- LeetCode 821 Shortest Distance to a Character 解题报告
题目要求 Given a string S and a character C, return an array of integers representing the shortest dista ...
- [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 ...
随机推荐
- [转帖]Linux系统进程的知识总结,进程与线程之间的纠葛...
Linux系统进程的知识总结,进程与线程之间的纠葛... https://cloud.tencent.com/developer/article/1500509 当一个程序开始执行后,在开始执行到执行 ...
- Quartz.Net—DateBuilder
定时框架中最重要的就是时间,我们也可以直接使用Cron这种事件格式. 使用其他的时间格式,就可以用DateBuilder快速的创建出需要的时间. 因为quartz是一个定时框架,所以对于操控时间 ...
- flask返回数据类型
服务器这种后台返回的数据只能是string,json或者是文件类型,对应Html的解析文件类型 无法返回自定义的元组,只能返回规定好的元组,说白了只第一个元素有效 所有返回前台的内容其实都应该是Res ...
- python3快速安装升级pip3
一.下载地址: 获取get-pip.py安装文件: 官网链接:https://bootstrap.pypa.io/get-pip.py 百度云链接:https://pan.baidu.com/s/14 ...
- Java 总结篇1
初始Java 1.Java的特点: ① 跨平台(字节码文件可以在任何具有Java虚拟机的计算机或者电子设备上运行,Java虚拟机中的Java解释器负责将字节码文件解释成特定的机器码进行运行) ② 简单 ...
- zookeeper启动占用8080端口,跟HDFS默认使用的8080端口冲突
zookeeper最近的版本中有个内嵌的管理控制台是通过jetty启动,也会占用8080 端口. 通过查看zookeeper的官方文档,发现有3种解决途径: (1).删除jetty. (2)修改端口. ...
- 在论坛中出现的比较难的sql问题:33(递归 连续日期问题 )
原文:在论坛中出现的比较难的sql问题:33(递归 连续日期问题 ) 最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了. 所以,觉得有必 ...
- Python-demo(抖音)
# -*- coding:utf-8 -*- from mitmproxy import ctx import json import requests import time import os p ...
- Spring Boot整合Spring Session实战
传统java web应用session都是由应用服务器(如tomcat)保存在内存中,这对应但节点应用来说没问题:但对于应用集群来说会造成各节点之间的session无法共享,一个节点挂掉后,其他节点接 ...
- Java Web-JQuery学习
Java Web-JQuery学习 JQuery概念 是一个JS框架,可以用来简化JS的开发,设计宗旨是"write less,do more",即写更少的代码,做更多的事情.它封 ...