之前听朋友说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的更多相关文章

  1. [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 ...

  2. LeetCode Shortest Distance from All Buildings

    原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...

  3. 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的值. 最 ...

  4. [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 ...

  5. [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 ...

  6. [LeetCode] Shortest Distance to a Character 到字符的最短距离

    Given a string S and a character C, return an array of integers representing the shortest distance f ...

  7. 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 ...

  8. LeetCode 317. Shortest Distance from All Buildings

    原题链接在这里:https://leetcode.com/problems/shortest-distance-from-all-buildings/ 题目: You want to build a ...

  9. 317. Shortest Distance from All Buildings

    题目: Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where th ...

随机推荐

  1. C# Http方式下载文件到本地

    下文代码是从网络(http://www.cnblogs.com/hayden/archive/2012/04/26/2472815.html)得来,亲测好用.我中修改了下格式和注释,版权属于原作者“舒 ...

  2. jquery 的父子节点

    1.一级父节点 parent() n级父节点 parents(???). 2.一级子节点 children() n级子节点  用find(???)

  3. C#中??和?分别是什么意思? 在ASP.NET开发中一些单词的标准缩写 C#SESSION丢失问题的解决办法 在C#中INTERFACE与ABSTRACT CLASS的区别 SQL命令语句小技巧 JQUERY判断CHECKBOX是否选中三种方法 JS中!=、==、!==、===的用法和区别 在对象比较中,对象相等和对象一致分别指的是什么?

    C#中??和?分别是什么意思? 在C#中??和?分别是什么意思? 1. 可空类型修饰符(?):引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空.例如:string str=null; ...

  4. php empty、isset、is_null区别

    有关 PHP 的 empty(),isset() 还有 is_null() 这三个函数的用法讨论得已经很多了,而且很多资料也未必能说得很清楚.这里再重复一次,但不是从概念去说,直接用程序例子来说话,应 ...

  5. ORACLE 11G 单实例 磁盘文件系统 DG 归档日志删除脚本 基于RED HAT LINUX 5.3 X86 64BIT

    近期做个DG的归档日志删除, [oracle@.local logs]crontab -l * 8 * * * sh /home/oracle/dbscripts/del_arc.sh 该脚本分别调用 ...

  6. kubernetes调度之资源耗尽处理配置

    系列目录 本篇将介绍如何使用kubelet处理资源耗尽的情况 当可用的计算机资源非常低的时候,kubelet仍然要保证节点的稳定性.当处理不可压缩的计算机资源(比如内存或磁盘空间)时,这尤其重要,当这 ...

  7. springboot中tomcat找不到jsp页面【转载】

    这个原理还没搞明白,只知道是内嵌的tomcat找jsp时默认不读取resources目录,但是具体的默认读取的是哪个目录,打了一下午断点我也没找到.... 修改方式,添加配置修改tomcat的读取目录 ...

  8. EasyDarwin EasyCamera支持海康摄像机接入了

    本文转自EasyDarwin开源团队成员Alex的博客:http://blog.csdn.net/cai6811376/article/details/52709816 EasyCamera默认使用海 ...

  9. RTSP流媒体转发服务器源码

    最新EasyDarwin已经支持海康.大华等标准RTSP/RTP协议的转发,代码及使用方法参看:用Darwin开发RTSP级联服务器(拉模式转发)http://blog.csdn.net/xiejia ...

  10. macos下查看用户组,以及修改文件权限

    查看当前用户所属组 groups 查看指定用户所属组 groups username 更改权限 将单个文件更改为777权限 chmod 777 aaa.txt 更改文件夹所属组 sudo chown ...