Description

Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, one, two), find a place to build a post office so that the sum of the distance from the post office to all the houses is smallest.

Return the smallest sum of distance. Return -1 if it is not possible.

  • You cannot pass through wall and house, but can pass through empty.
  • You only build post office on an empty.

Example

Example 1:

Input:[[0,1,0,0,0],[1,0,0,2,1],[0,1,0,0,0]]
Output:8
Explanation: Placing a post office at (1,1), the distance that post office to all the house sum is smallest.

Example 2:

Input:[[0,1,0],[1,0,1],[0,1,0]]
Output:4
Explanation: Placing a post office at (1,1), the distance that post office to all the house sum is smallest.

Challenge

Solve this problem within O(n^3) time.

思路:

  • 本题采用bfs,首次遍历网格,对空地处进行bfs,搜索完成后如果存在房屋没有被vis标记则改空地不可以设置房屋。
  • 朴素的bfs搜索过程中,sun+=dist;实现当前点距离和的更新。
  • now.dis+1每次实现当前两点间距离的更新。
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
} public class Solution {
public int EMPTY = 0;
public int HOUSE = 1;
public int WALL = 2;
public int[][] grid;
public int n, m;
public int[] deltaX = {0, 1, -1, 0};
public int[] deltaY = {1, 0, 0, -1}; private List<Coordinate> getCoordinates(int type) {
List<Coordinate> coordinates = new ArrayList<>(); for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == type) {
coordinates.add(new Coordinate(i, j));
}
}
} return coordinates;
} private void setGrid(int[][] grid) {
n = grid.length;
m = grid[0].length;
this.grid = grid;
} private boolean inBound(Coordinate coor) {
if (coor.x < 0 || coor.x >= n) {
return false;
}
if (coor.y < 0 || coor.y >= m) {
return false;
}
return grid[coor.x][coor.y] == EMPTY;
} /**
* @param grid a 2D grid
* @return an integer
*/
public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return -1;
} // set n, m, grid
setGrid(grid); List<Coordinate> houses = getCoordinates(HOUSE);
int[][] distanceSum = new int[n][m];
int[][] visitedTimes = new int[n][m];
for (Coordinate house : houses) {
bfs(house, distanceSum, visitedTimes);
} int shortest = Integer.MAX_VALUE;
List<Coordinate> empties = getCoordinates(EMPTY);
for (Coordinate empty : empties) {
if (visitedTimes[empty.x][empty.y] != houses.size()) {
continue;
} shortest = Math.min(shortest, distanceSum[empty.x][empty.y]);
} if (shortest == Integer.MAX_VALUE) {
return -1;
}
return shortest;
} private void bfs(Coordinate start,
int[][] distanceSum,
int[][] visitedTimes) {
Queue<Coordinate> queue = new LinkedList<>();
boolean[][] hash = new boolean[n][m]; queue.offer(start);
hash[start.x][start.y] = true; int steps = 0;
while (!queue.isEmpty()) {
steps++;
int size = queue.size();
for (int temp = 0; temp < size; temp++) {
Coordinate coor = queue.poll();
for (int i = 0; i < 4; i++) {
Coordinate adj = new Coordinate(
coor.x + deltaX[i],
coor.y + deltaY[i]
);
if (!inBound(adj)) {
continue;
}
if (hash[adj.x][adj.y]) {
continue;
}
queue.offer(adj);
hash[adj.x][adj.y] = true;
distanceSum[adj.x][adj.y] += steps;
visitedTimes[adj.x][adj.y]++;
} // direction
} // for temp
} // while
}
}

  

Build Post Office II的更多相关文章

  1. Build Post Office

    Description Given a 2D grid, each cell is either an house 1 or empty 0 (the number zero, one), find ...

  2. 九章lintcode作业题

    1 - 从strStr谈面试技巧与代码风格 必做题: 13.字符串查找 要求:如题 思路:(自写AC)双重循环,内循环读完则成功 还可以用Rabin,KMP算法等 public int strStr( ...

  3. BFS总结

    能够用 BFS 解决的问题,一定不要用 DFS 去做! 因为用 Recursion 实现的 DFS 可能造成 StackOverflow! (NonRecursion 的 DFS 一来你不会写,二来面 ...

  4. EDKII Build Process:EDKII项目源码的配置、编译流程[三]

    <EDKII Build Process:EDKII项目源码的配置.编译流程[3]>博文目录: 3. EDKII Build Process(EDKII项目源码的配置.编译流程) -> ...

  5. Post Office Problem

    Description There are n houses on a line. Given an array A and A[i] represents the position of i-th  ...

  6. BNUOJ 2947 Buy Tickets

    Buy Tickets Time Limit: 4000ms Memory Limit: 65536KB This problem will be judged on PKU. Original ID ...

  7. 斯坦福 CS183 & YC 创业课系列中文笔记

    欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远. 在线阅读 ApacheCN 面试求职交流群 724187166 ApacheCN 学习资源 目录 Zero to One 从0到1 ...

  8. sharepoint OOS巨大坑

    首先,我们安装的操作系统是windows server 2016 datacenter最新版,然后安装了OOS2016年的那个版本,打好语言包,安装必备软件,所有的步骤都没问题,但是你配置OOS场的时 ...

  9. How to Build Office Developer Tools Projects with TFS Team Build 2012

    Introduction Microsoft Visual Studio 2012 provides a new set of tools for developing apps for Office ...

随机推荐

  1. Resouce Pool的理解

    本篇文章从现象到本质再到具象去理解 , 从理论到实战再到源码回顾去深化. 1.在开发中,无处不在的池. eg 网络通信连接池: HttpClient连接池 HttpClient通过PoolingHtt ...

  2. LeetCode 5198. 丑数 III(Java)容斥原理和二分查找

    题目链接:5198. 丑数 III 请你帮忙设计一个程序,用来找出第 n 个丑数. 丑数是可以被 a 或 b 或 c 整除的 正整数. 示例 1: 输入:n = 3, a = 2, b = 3, c ...

  3. Linux下使用strip如何对库和可执行文件进行裁减

    如果生成的可执行文件或库比较大,这时候就可以使用strip命令进行裁减,在嵌入式开发中,如果使用的交叉编译工具是arm-linux,则命令 是arm-linux-strip,如果是arm-uclibc ...

  4. BZOJ1060或洛谷1131 [ZJOI2007]时态同步

    BZOJ原题链接 洛谷原题链接 看上去就觉得是一道树形\(\mathtt{DP}\),不过到头来我发现我写了一个贪心.. 显然对越靠近根(记为\(r\))的边进行加权贡献越大,且同步的时间显然是从根到 ...

  5. IDEA debug断点调试技巧

    Debug用来追踪代码的运行流程,通常在程序运行过程中出现异常,启用Debug模式可以分析定位异常发生的位置,以及在运行过程中参数的变化.通常我们也可以启用Debug模式来跟踪代码的运行流程去学习三方 ...

  6. spring Boot 学习(五、Spring Boot与安全)

    一.安全Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模 块默认的技术选型.他可以实现强大的web安全控制.对于安全控制,我们仅 需引入spring ...

  7. Windows查看端口使用状况(转)

    转:https://www.cnblogs.com/lixuwu/p/5898354.html 阅读目录 1 查看windows所有端口进程 2 查询指定端口 使用端口是我们在进行远程或者打印机等都会 ...

  8. webpack练手项目之easySlide(二):代码分割

    Hello,大家好. 在上一篇 webpack练手项目之easySlide(一):初探webpack  中我们一起为大家介绍了webpack的基本用法,使用webpack对前端代码进行模块化打包. 但 ...

  9. Leetcode刷题python

    Two Sum 两数==target 方法二更好 题1,对时间复杂度有要求O(n),所以维护一个字典,遍历过的数值放在字典中,直接遍历时候查找字典中有没有出现差,查找字典时间复杂度是O(1),所以O( ...

  10. postman 在pre-request中发送application/x-www-form-urlencoded 格式表单

    postman中在pre-request 发送请求 知识点: json数据解析和遍历 application/x-www-form-urlencoded表单 Array基本使用 js函数 http请求 ...