[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 ...
随机推荐
- DICOM医学图像处理:深入剖析Orthanc的SQLite,了解WADO & RESTful API
背景: 上一篇博文简单翻译了Orthanc官网给出的CodeProject上“利用Orthanc Plugin SDK开发WADO插件”的博文,其中提到了Orthanc从0.8.0版本之后支持快速查询 ...
- Maven引入本地Jar包并打包进War包中
1.概述 在平时的开发中,有一些Jar包因为种种原因,在Maven的中央仓库中没有收录,所以就要使用本地引入的方式加入进来. 2. 拷贝至项目根目录 项目根目录即pom.xml文件所在的同级目录,可以 ...
- PS 基础知识 .atn文件如何使用
ANT文件就是Frames.atn类动作文件 具体安装步骤如下 : (以CS4 为例) 启动Photoshop 点击"窗口" 选"动作" 在弹出的动作面板里,点 ...
- 几个关于tableView的问题解决方式整合
近期遇到关于tableView的问题的整合.部分比較白痴.仅仅是初学easy犯~ 1.关于tableView左边空余15像素的问题. 2.关于tableView多余切割线隐藏的问题: 3.关于tabl ...
- centos 使用 CP 命令 不提示 覆盖
今天 在我的VPS上拷一个目录,但放的地方有一个同名目录并且里面还有文件.如是直接拷过去,结果有N个要确认替换的提示,直接CTRL+C,在网上搜了把,发现有几个方法能够解决,方法例如以下: 一般我们使 ...
- android实例讲解----Tomcat部署Web应用方法总结
参考文档:http://blog.csdn.net/yangxueyong/article/details/6130065 Tomcat部署Web应用方法总结 一.架构介 ...
- Cocos2d-x 3.0final 终结者系列教程15-win7+vs2012+adt+ndk环境搭建(无Cygwin)
最终不用Cygwin 了.非常高兴 为什么要用Win7? 由于VS2012要求Win7以上系统才干安装! 为什么要用vs2012? 由于VS2012才支持C++11! 为什么要支持C++11? 由于C ...
- HTML5开发移动web应用——Sencha Touch篇(7)
Sencha Touch中的Ext.DomHelper组件能够方便的实现对元素的追加或重写操作 演示样例: launch:function(){ function appendDom(){ Ext.D ...
- 图像处理之滤波---gabor
http://blog.csdn.net/xiaowei_cqu/article/details/24745945 小魏北大
- Linux学习笔记--ps命令(显示当前进程的命令)
ps:英文名process,进程的意思. 1. 命令格式: ps [选项] 2. 经常使用选项: "ps -a" 显示一个终端的全部进程.除了会话引线 "ps -e&qu ...