之前听朋友说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. Qt中QVector与QList的应用

    首先來看看QVector 的基本使用方式,建立一個可容納兩個元素的QVector ,並使用索引方式存取元素值:QVector<double> vect(2); vect[0] = 1.0; ...

  2. minimum-moves-to-equal-array-elements-ii(好)

    https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ package com.company; import ...

  3. [反汇编练习] 160个CrackMe之037

    [反汇编练习] 160个CrackMe之037. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...

  4. C# 使用xenocode混淆加密【转】

    http://www.cnblogs.com/chendaoyin/archive/2013/05/03/3056692.html   之前就了解过混淆加密工具,但这还是第一次使用,选择了xenoco ...

  5. Linux Distribution

    来自为知笔记(Wiz)

  6. mysql 授权新的root用户

    grant all privileges to *.* on system@'localhost' identified by 'woshishui' with grant option;

  7. angular - 安装 -1

    在阅读以下教程以前,请安装node,请先确保您的使用平台:Win.Mac.Linux 首次安装node以后,我们先检测版本 node -v npm -v 这样就代表安装成功,那么我们可以进入下一步了 ...

  8. Odoo calendar 提醒器

    Odoo calendar 提供了一个提醒功能,它包含邮件通知以及web client弹窗功能     创建日历事件的时候,可以设置提醒器     Meeting [ calendar.event ] ...

  9. Nginx下的https配置

    https: https(Secure Hypertext Transfer Protocol) 安全超文本传输协议 它是以安全为目标的http通道,即它是http的安全版.它使用安全套接字层(SSL ...

  10. android-async-http框架

    android-async-http 简单介绍:An asynchronous, callback-based Http client for Android built on top of Apac ...