[LeetCode] Shortest Distance from All Buildings Solution
之前听朋友说LeetCode出了一道新题,但是一直在TLE,我就找时间做了一下。这题是一个比较典型的BFS的题目,自己匆忙写了一个答案,没有考虑优化的问题,应该是有更好的解法的。
原题如下:
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的点就加上相应的距离。这题因为要求到所有1的距离和最小的点,所以就可以无脑iterate over所有数值为1的点,并开一个二维数组来记录各个点的累加距离值。最后要检查一下所有结果中的值,确保其可以reach到所有的值为1的点,若不存在这样的,则返回-1。代码如下,比较冗长,等有机会再优化一下吧。
public class Solution {
public int shortestDistance(int[][] grid) {
int result = Integer.MAX_VALUE;
boolean[][] done = new boolean[grid.length][grid[0].length];
int[][] cost = new int[grid.length][grid[0].length];
int[][] count = new int[grid.length][grid[0].length];
int total = 0; // total # of 1
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
done[i][j] = grid[i][j] != 0;
total = grid[i][j] == 1 ? total + 1 : total;
}
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
Deque<Integer> row = new ArrayDeque<>();
Deque<Integer> col = new ArrayDeque<>();
enqueue(row, col, i, j, done, grid);
bfs(row, col, grid, cost, done, count, 1);
}
}
}
if (!isValid(count, total)) {
return -1;
}
for (int i = 0; i < cost.length; i++) {
for (int j = 0; j < cost[0].length; j++) {
if (count[i][j] == total) {
result = cost[i][j] > 0 ? Math.min(result, cost[i][j]) : result;
}
}
}
return result;
} private void bfs(Deque<Integer> row, Deque<Integer> col, int[][] grid, int[][] cost, boolean[][] done, int[][] count, int distance) {
if (row.isEmpty()) {
return;
}
int size = row.size();
List<Integer> row1 = new ArrayList<>();
List<Integer> col1 = new ArrayList<>();
for (int k = 0; k < size; k++) {
int i = row.poll();
int j = col.poll();
row1.add(i);
col1.add(j);
cost[i][j] += distance;
count[i][j] += 1;
enqueue(row, col, i, j, done, grid);
}
bfs(row, col, grid, cost, done, count, distance + 1);
for (int i = 0; i < row1.size(); i++) {
done[row1.get(i)][col1.get(i)] = false;
}
} private void enqueue(Deque<Integer> row, Deque<Integer> col, int i, int j, boolean[][] done, int[][] grid) {
int down = i + 1;
int up = i - 1;
int left = j - 1;
int right = j + 1;
if (up >= 0 && !done[up][j] && grid[up][j] == 0) {
row.offer(up);
col.offer(j);
done[up][j] = true;
}
if (down < grid.length && !done[down][j] && grid[down][j] == 0) {
row.offer(down);
col.offer(j);
done[down][j] = true;
}
if (left >= 0 && !done[i][left] && grid[i][left] == 0) {
row.offer(i);
col.offer(left);
done[i][left] = true;
}
if (right < grid[0].length && !done[i][right] && grid[i][right] == 0) {
row.offer(i);
col.offer(right);
done[i][right] = true;
}
} private boolean isValid(int[][] count, int total) {
for (int[] aCount : count) {
for (int c : aCount) {
if (c == total) {
return true;
}
}
}
return false;
}
}
[LeetCode] Shortest Distance from All Buildings Solution的更多相关文章
- [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 ...
- 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] 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 to a Character 到字符的最短距离
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 317. 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 ...
随机推荐
- Android 自定义录音、播放动画View,让你的录音浪起来
最近公司项目有一个录音的录制和播放动画需求,然后时间是那么紧,那么赶紧开撸. 先看效果图 嗯,然后大致就是这样,按住录音,然后有一个倒计时,最外层一个进度条,还有一个类似模拟声波的动画效果(其实中间的 ...
- 修改ViewPager调用setCurrentItem时,滑屏的速度 ,解决滑动之间切换动画难看
在使用ViewPager的过程中,有需要直接跳转到某一个页面的情况,这个时候就需要用到ViewPager的setCurrentItem方法了,它的意思是跳转到ViewPager的指定页面,但在使用这个 ...
- 织梦dedecms 去掉后台登陆验证码的方法
那么有什么办法解决呢? 那么现在就给大家解决织梦去掉后台登陆验证码. 这里面分两种版本 一个是织梦5.6的程序 那么织梦5.6程序的解决办法是: 在织梦DedeCms5.6版本可以通过下面路径对验 ...
- utuntu16.04安装caffe+Matlab2017a+opencv3.1+CUDA8.0+cudnn6.0
上午把tensorflow安装好了,下午和晚上装caffe的确很费劲. 默认CUDA,cuDNN可以用了 caffe官方安装教程 有些安装顺序自己也不清楚,简直就是碰运气 1. 安装之前依赖项 Gen ...
- install nfs and share file
介绍一下NFS的安装,以及共享文件 NFS(Net File System),通过使用NFS,可以像使用本地文件一样访问远程文件. 它主要解决了数据共享的问题,可以备份容灾. 安装配置 1.以linu ...
- C# 将链表存入二进制文件及读取二进制文件得到链表示例
// 将tasks保存到二进制文件中 public Boolean saveToFile(String file) { try { ) { // 没任务就不存 return false; } if ( ...
- sql导入数据库
有问题可以尝试加上这句 DROP TABLE IF EXISTS `t_saler_login_log`;
- linux find prune排除某目录或文件
http://blog.csdn.net/ysdaniel/article/details/7995681 查找cache目录下不是html的文件 find ./cache ! -name '*.ht ...
- Ionic + AngularJS angular-translate 国际化本地化解决方案
欢迎访问我们的网站,网站上有更多关于技术性的交流:http://www.ncloud.hk/技术分享/ionic-plus-angularjs-angular-translate-国际化本地化解决方案 ...
- Python编写的ARP扫描工具
源码如下: rom scapy.all import * import threading import argparse import logging import re logging.getLo ...