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 ...
随机推荐
- Java中的事务及使用
什么是事务? 事务(Transaction),一般是指要做的或所做的事情.在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit).事务通常由高级数据库操纵语言或编程语言(如S ...
- 【坑】SpringMvc 处理JSON 乱码
文章目录 前言 方法 前言 在使用 springMvc 的时候,如果向前台返回 JSON 数据,JSON 中的中文会乱码: 即使你在配置了全局的信息编码拦截器,也无济于事: 原因大抵是,JSON 的内 ...
- Python【变量和赋值】
name = '千变万化' #把“千变万化”赋值给了“name”这个[变量] >>> name = '一'>>> name = '二'>>> pr ...
- 信息的Raid存储方式,更安全的保障,更花钱的保障!
raid0 就是把多个(最少2个)硬盘合并成1个逻辑盘使用,数据读写时对各硬盘同时操作,不同硬盘写入不同数据,速度快. raid1就是同时对2个硬盘读写(同样的数据).强调数据的安全性.比较浪费. r ...
- 史上最全最新Java面试题合集一(附答案)
下面小编整理了本套java面试题全集,分享给大家,希望对大家的java学习和就业面试有所帮助. 1.面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面: 抽象:抽象是将一类对象的共同特征 ...
- python pip命令安装相当于yum仓库
进入pip目录: 创建pip.conf: 打开pip.conf [global] index-url=https://mirrors.aliyun.com/pypi/simple/ trusted-h ...
- 案例(2)-- 线程不安全对象(SimpleDateFormat)
问题描述: 1.系统偶发性抛出异常:java.lang.NumberFormatException: multiple points ,追溯源头抛出的类为:SimpleDateFormat 问题的定位 ...
- websocket 协议简述
WebSocket 是一种网络通信协议,RFC 6455 定义了它的通信标准,属于服务器推送技术的一种 由于 HTTP 无状态.无连接.单向通信的特性,导致 HTTP 协议无法实现服务器主动向客户端发 ...
- Qt4 和 Qt5 模块的分类
Qt5 与 Qt4 其中的一个区别是底层架构进行了改变,Qt5 引入了更加详细的模块化的概念,将众多功能细分到几个模块之中,Qt4 则是一种粗略的划分.本文主要对 Qt5 和 Qt4的模块进行一个简单 ...
- Go part 8 并发编程,goroutine, channel
并发 并发是指的多任务,并发编程含义比较广泛,包含多线程.多进程及分布式程序,这里记录的并发是属于多线程编程 Go 从语言层面上支持了并发的特性,通过 goroutine 来完成,goroutine ...