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 ...
随机推荐
- 关于String Json 与其他类型数据转换的总结:
一:关于自己遇到的坑: 跨域请求获取到 String Json(GSON处理) 数据后处理转换为实体类进行存储: 跨域 return Gson.toJson(map): 通过Http等方法获取请求结果 ...
- C++中数组占用的内存计算
在C++中int类型每个空间是4个字节,long long int 是8个字节,而bool类型是1个字节 所以一般能用bool就别用int,节约空间 数组占用内存的计算 a[1001][1001]的空 ...
- windows密码凭据
- python 之 并发编程(守护线程与守护进程的区别、线程互斥锁、死锁现象与递归锁、信号量、GIL全局解释器锁)
9.94 守护线程与守护进程的区别 1.对主进程来说,运行完毕指的是主进程代码运行完毕2.对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕详细解释:1.主 ...
- on duplicate key mysql插入更新
insert into `test` (`job_id`, `user_name`, `total_time`) values ('12345', 'zhangsan', '10') on dupli ...
- Hibernate持久化,生命周期
一 .生命周期 1.1 . 说明 持久化类就是我们所说的实体类,实体类(持久化类)对象是有状态的. 为什么实体类对象会有状态? 答:由于HIbernate框架是一个先映射,后操作的框架.所谓的状 ...
- L2范数归一化概念和优势
1 归一化处理 归一化是一种数理统计中常用的数据预处理手段,在机器学习中归一化通常将数据向量每个维度的数据映射到(0,1)或(-1,1)之间的区间或者将数据向量的某个范数映射为1,归一化 ...
- openfeign与gateway中的httpClient类声明冲突
启动spring cloud中的网关,报错: ***************************APPLICATION FAILED TO START*********************** ...
- IServiceBehavior IContractBehavior IEndpointBehavior IOperationBehavior
using System; using System.Collections.ObjectModel; using System.Reflection; using System.ServiceMod ...
- http://go.microsoft.com/fwlink/?linkid问题
今天不知怎的,打开一个网页出现了http://go.microsoft.com/fwlink/?linkid=XXX 烦死了,在百度搜了下方法,什么改注册表,策略模板等不见起效.其实打开IE的设置, ...