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.
For example, given three buildings at (0,0)
, (0,4)
, (2,2)
, and an obstacle at (0,2)
:
1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
The 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.
思路:
从每个点是1的点出发,通过bfs找到这个点到每个0点最短距离,同时记录该0点被1点访问过的次数。这样我们遍历所有1点,对所有能够被访问到的1点,保存最短距离以及增加访问次数。最后把所有0点遍历一遍,看它是否被所有1点访问到,并且最短距离和最小。
其实这里也可以从0出发,做类似的事情。选1还是0看它们的个数。谁小就选谁。
public class Solution {
private int[][] dir = { { -, }, { , }, { , - }, { , } }; public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == ) {
return ;
} int rows = grid.length, cols = grid[].length, numBuildings = ;
int[][] reach = new int[rows][cols], distance = new int[rows][cols]; // Find the minimum distance from all buildings
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == ) {
shortestDistanceHelper(i, j, grid, reach, distance);
numBuildings++;
}
}
} // step 2: check the min distance reachable by all buildings
int minDistance = Integer.MAX_VALUE;
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == && reach[i][j] == numBuildings && distance[i][j] < minDistance) {
minDistance = distance[i][j];
}
}
}
return minDistance == Integer.MAX_VALUE ? - : minDistance;
} private void shortestDistanceHelper(int row, int col, int[][] grid, int[][] reach, int[][] distance) {
int rows = grid.length, cols = grid[].length, d = ;
boolean[][] visited = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] { row, col });
visited[row][col] = true;
while (!queue.isEmpty()) {
d++;
int size = queue.size();
for (int j = ; j < size; j++) {
int[] cord = queue.poll();
for (int i = ; i < ; i++) {
int rr = dir[i][] + cord[];
int cc = dir[i][] + cord[];
if (isValid(rr, cc, grid, visited)) {
queue.offer(new int[] { rr, cc });
visited[rr][cc] = true;
reach[rr][cc]++;
distance[rr][cc] += d;
}
}
}
}
} private boolean isValid(int row, int col, int[][] grid, boolean[][] visited) {
int rows = grid.length, cols = grid[].length;
if (row < || row >= rows || col < || col >= cols || visited[row][col] || grid[row][col] == ) {
return false;
}
return true;
}
}
Shortest Distance from All Buildings的更多相关文章
- [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 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的值. 最 ...
- [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 ...
- [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 ...
- LeetCode Shortest Distance from All Buildings
原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...
- 317. Shortest Distance from All Buildings
题目: Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where th ...
- [Swift]LeetCode317. 建筑物的最短距离 $ 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] Shortest Distance from All Buildings Solution
之前听朋友说LeetCode出了一道新题,但是一直在TLE,我就找时间做了一下.这题是一个比较典型的BFS的题目,自己匆忙写了一个答案,没有考虑优化的问题,应该是有更好的解法的. 原题如下: You ...
- LeetCode 317. Shortest Distance from All Buildings
原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...
随机推荐
- 校验正确获取对象或者数组的属性方法(babel-plugin-idx/_.get)
背景: 开发中经常遇到取值属性的时候,需要校验数值的有效性. 例如: 获取props对象里面的friends属性 props.user && props.user.friends &a ...
- 【线性代数】2-1:解方程组(Ax=b)
title: [线性代数]2-1:解方程组(Ax=b) toc: true categories: Mathematic Linear Algebra date: 2017-08-31 15:08:3 ...
- Depth from Videos in the Wild 解读
2019年7月17日11:37:05 论文 Depth from Videos in the Wild: Unsupervised Monocular Depth Learning from Unkn ...
- Django从Models 10分钟定制一个Admin后台
目录 Django从Models 10分钟建立一套RestfulApi Django从Models 10分钟定制一个Admin后台 简介 Django自带一个Admin后台, 支持用户创建,权限配置和 ...
- 第三章 python数据规整化
本章概要 1.去重 2.缺失值处理 3.清洗字符型数据的空格 4.字段抽取 去重 把数据结构中,行相同的数据只保留一行 函数语法: drop_duplicates() #导入pandas包中的read ...
- Python字典元素的增加删除和取出字典所有的键和值
一.增加一个或多个元素 d = {'a': 1} d.update(b=2) #也可以 d.update({‘b’: 2}) print(d) # {'a': 1, 'b': 2} d['e'] = ...
- AtCoder AGC001E BBQ Hard (DP、组合计数)
题目链接: https://atcoder.jp/contests/agc001/tasks/agc001_e 题解: 求\(\sum^n_{i=1}\sum^n_{j=i+1} {A_i+A_j+B ...
- UVA 247 Calling Circles —— (强连通分量模板题)
第一个强连通分量的题. 题意:有一堆人,a给b打电话表示a有一条向b的边,一个强连通分量代表一个电话圈,把每个电话圈里的人在一行内输出出来. 直接上模板即可,但是要注意把string用map映射一下的 ...
- DS-博客作业07
1.本周学习总结(0--2分) 1.1思维导图 1.2 谈谈你对查找运算的认识及学习体会. 在查找这一章,我学习的比较认真,但是还是有部分没太清楚.这章没有前一章树那么多的代码要记,但是还是要用心. ...
- 数据库 | SQL语法优化方法及实例详解
使用复合索引 如果经常执行如上查询,那么建立三个单独索引不如建立一个复合索引,因为三个单独索引通常数据库每次执行只能使用其中一个,虽然这样比不使用索引而进行全表扫描提高了很多效率,但使用复合索引因为索 ...