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. beanshell 通过java写数据到文件

    import java.io.*; String filePath = "/data/account.txt"; String conent = vars.get("ac ...

  2. ACM算法锦集

    一:知识点 数据结构: 1,单,双链表及循环链表 2,树的表示与存储,二叉树(概念,遍历)二叉树的 应用(二叉排序树,判定树,博弈树,解答树等) 3,文件操作(从文本文件中读入数据并输出到文本文 件中 ...

  3. 嵌入式02 STM32 实验09 独立/窗口看门狗

    一.独立看门狗和窗口看门狗 看门狗:单片机系统在外界的干扰下会出现程序跑飞的现象导致死循环,或者崩溃,看门狗电路就是为了避免这种情况的发生,看门狗的作用就是在一定的事件内(通过计数器实现)若没有收到喂 ...

  4. 用Scratch制作一个Hello World程序

    网上出现了很多Hello World程序,看的小编心里也痒痒的,为此这次作为南京小码王Scratch培训机构的小编,就为大家来详细的了解下Scratch制作Hello World程序的过程,现在就和小 ...

  5. rancher部署kubernets集群

    docker的安装 先添加docker源 sudo apt update sudo apt install docker.io docker更换国内镜像 1.配置脚本如下: #!/bin/bashca ...

  6. .NET Core微服务学习-DotNetty

    DotNetty介绍: DotNetty是Azure团队仿照(几乎可以这么说)JAVA的Netty而出来的(目前已实现Netty的一部分),目前在Github上的Star有1.8K+, 地址:http ...

  7. (转)微服务_.NET Core Consul服务发现与治理

    原文地址:https://www.cnblogs.com/waynechan/p/9354909.html Consul官网:https://www.consul.io Consul下载地址:http ...

  8. java之spring之scope和autowiring

    目录结构如下: UserDao.java package cn.sxt.dao; public interface UserDao { public void add(); } UserDaoImpl ...

  9. 2019 华云数据java面试笔试题 (含面试题解析)

    本人3年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.华云数据等公司offer,岗位是Java后端开发,最终选择去了华云数据. 面试了很多家公司,感觉大部分公司考察的点 ...

  10. crunch制作字典

    安装 安装crunch sudo apt-get install crunch 语法 crunch <min> max<max> <characterset> -t ...