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点最短距离,同时记录该0点被1点访问过的次数。这样我们遍历所有1点,对所有能够被访问到的1点,保存最短距离以及增加访问次数。最后把所有0点遍历一遍,看它是否被所有1点访问到,并且最短距离和最小

其实这里也可以从0出发,做类似的事情。选1还是0看它们的个数。谁小就选谁。

 public class Solution {
private int[][] dir = { { -, }, { , }, { , - }, { , } }; public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == ) {
return ;
} int rows = grid.length, cols = grid[].length, numBuildings = ;
int[][] reach = new int[rows][cols], distance = new int[rows][cols]; // Find the minimum distance from all buildings
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == ) {
shortestDistanceHelper(i, j, grid, reach, distance);
numBuildings++;
}
}
} // step 2: check the min distance reachable by all buildings
int minDistance = Integer.MAX_VALUE;
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (grid[i][j] == && reach[i][j] == numBuildings && distance[i][j] < minDistance) {
minDistance = distance[i][j];
}
}
}
return minDistance == Integer.MAX_VALUE ? - : minDistance;
} private void shortestDistanceHelper(int row, int col, int[][] grid, int[][] reach, int[][] distance) {
int rows = grid.length, cols = grid[].length, d = ;
boolean[][] visited = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] { row, col });
visited[row][col] = true;
while (!queue.isEmpty()) {
d++;
int size = queue.size();
for (int j = ; j < size; j++) {
int[] cord = queue.poll();
for (int i = ; i < ; i++) {
int rr = dir[i][] + cord[];
int cc = dir[i][] + cord[];
if (isValid(rr, cc, grid, visited)) {
queue.offer(new int[] { rr, cc });
visited[rr][cc] = true;
reach[rr][cc]++;
distance[rr][cc] += d;
}
}
}
}
} private boolean isValid(int row, int col, int[][] grid, boolean[][] visited) {
int rows = grid.length, cols = grid[].length;
if (row < || row >= rows || col < || col >= cols || visited[row][col] || grid[row][col] == ) {
return false;
}
return true;
}
}

Shortest Distance from All Buildings的更多相关文章

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

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

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

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

  5. LeetCode Shortest Distance from All Buildings

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

  6. 317. Shortest Distance from All Buildings

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

  7. [Swift]LeetCode317. 建筑物的最短距离 $ 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] Shortest Distance from All Buildings Solution

    之前听朋友说LeetCode出了一道新题,但是一直在TLE,我就找时间做了一下.这题是一个比较典型的BFS的题目,自己匆忙写了一个答案,没有考虑优化的问题,应该是有更好的解法的. 原题如下: You ...

  9. LeetCode 317. Shortest Distance from All Buildings

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

随机推荐

  1. 检查多个远程 Linux 系统是否打开了指定端口

    如果想检查 50 多台服务器是否打开了指定的端口,该怎么做,要检查所有服务器并不容易,如果你一个一个这样做,完全没有必要,因为这样你将会浪费大量的时间.为了解决这种情况,我使用 nc 命令编写了一个 ...

  2. Burpsuite 2.0.11 Beta 破解版下载

    1.解包 jar xvf burpsuite_pro_v2.0.11beta.jar 自行定制,删除自带chrome和7zip软件包之后,软件精简至39M. 2.打包 jar cvfm META-IN ...

  3. [Luogu] 计算系数

    https://www.luogu.org/problemnew/show/P1313#sub Answer = a ^ n * b ^ m * C(k, min(n,  m)) 这里用费马小定理求逆 ...

  4. 【CUDA 基础】5.3 减少全局内存访问

    title: [CUDA 基础]5.3 减少全局内存访问 categories: - CUDA - Freshman tags: - 共享内存 - 归约 toc: true date: 2018-06 ...

  5. Java字节码例子解析

    举个简单的例子: public class Hello {     public static void main(String[] args) {         String string1 = ...

  6. Final——PowerShell Empire

    一.介绍 Empire是一款针对Windows平台的.使用PowerShell脚本作为攻击载荷的渗透攻击框架工具,具有从stager生成.提权到渗透维持的一系列功能.Empire实现了无需powers ...

  7. vue active样式显示

    html:代码 <ul> <li @click="current='xxxx'" :class="{active:current=='xxxx'}&qu ...

  8. 在matlab中读取trc文件

    用matlab的load()函数 1.相对路径读法(将文件放入'MATLAB\bin'目录): a = load('aizhenjiang_g10.trc') 2.绝对路径读法(任何位置) a = f ...

  9. jQuery常用AJAX-API

    目的:简化客户端与服务端进行局部刷新的异步通讯 (1)取得服务端当前时间 简单形式:jQuery对象.load(url) 返回结果自动添加到jQuery对象代表的标签中间 如果是Servlet的话,采 ...

  10. NLP之电影评分数据的情感分析

    1.基于词袋模型的逻辑回归情感分类 # coding: utf-8 import re import numpy as np import pandas as pd from bs4 import B ...