LintCode 573 - Build Post Office I


https://zhengyang2015.gitbooks.io/lintcode/build_post_office_573.html
Given a 2D grid, each cell is either an house 1 or empty 0 (the number zero, one), find the place to build a post office, the distance that post office to all the house sum is smallest. Return the smallest distance. Return -1 if it is not possible.
Notice
You can pass through house and empty.
You only build post office on an empty.
Example
Given a grid:
0 1 0 0
1 0 1 1
0 1 0 0
return 6. (Placing a post office at (1,1), the distance that post office to all the house sum is smallest.)
这道题可以用dp来做,但是会超时。首先扫描一遍将所有house的点记录下来,然后遍历图中所有0的点,计算每个0的点到这些house的距离和,选最小的那个即可。这种情况下可以优化到O(k * n ^ 2),但是如果数据量很大还是过不了。
因此需要减少搜索的点。想到的方法是在所有房子围成的形状的重心位置附近建邮局则到所有房子的距离之和最短(怎么证明?)。因此步骤如下:
+

  1. 首先找到所有房子的重心。找所有房子x值的median和y值的median(如果是奇数个就是排序后取中间值,如果是偶数则取中间两个数再取平均值)即为重心。
  2. 然后用bfs来搜索。将重心加入queue中,然后开始一圈一圈(将出队的每个点周围八个点加入队中)向外找,用的是和逐层遍历二叉树的类似的方法(即在每一层开始的时候记录一下本层的点的个数,然后一次出队这么多点即可将本层的点全部出队)。每一圈结束时,返回该圈上的点作为post office能取的最小值,如果存在则停止搜索。即如果存在可以作为post office的点,则外圈点到各个房子的距离一定不会比内圈点更优。
median version
    class Node{
        int x;
        int y;
        public Node(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    int[] dx = {0, 0, -1, 1, -1, 1, -1, 1};
    int[] dy = {-1, 1, 0, 0, -1, -1, 1, 1};

    //Median version
    public int shortestDistance(int[][] grid) {
        // Write your code here
        if(grid == null || grid.length == 0 || grid[0].length == 0){
            return -1;
        }

        int n = grid.length;
        int m = grid[0].length;
        boolean[][] visit = new boolean[n][m];
        ArrayList<Node> house = new ArrayList<Node>();
        ArrayList<Integer> xArr = new ArrayList<Integer>();
        ArrayList<Integer> yArr = new ArrayList<Integer>();
        //find house position
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == 1){
                    house.add(new Node(i, j));
                    xArr.add(i);
                    yArr.add(j);
                }
            }
        }
        //no empty place
        if(house.size() == m * n){
            return -1;
        }

        if(house.size() == 0){
            return 0;
        }

        //find the median of house positions
        int xMedian = getMedian(xArr);
        int yMedian = getMedian(yArr);

        Queue<Node> queue = new LinkedList<Node>();
        queue.add(new Node(xMedian, yMedian));
        visit[xMedian][yMedian] = true;
        int min = Integer.MAX_VALUE;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                Node curt = queue.poll();
                if(grid[curt.x][curt.y] == 0){
                    min = Math.min(min, search(house, curt));
                }
                for(int j = 0; j < 8; j++){
                    int nextX = curt.x + dx[j];
                    int nextY = curt.y + dy[j];
                    if(nextX >= 0 && nextX < n && nextY >= 0 && nextY < m && !visit[nextX][nextY]){
                        visit[nextX][nextY] = true;
                        queue.add(new Node(nextX, nextY));
                    }
                }
            }
            if(min != Integer.MAX_VALUE){
                return min;
            }
        }

        return -1;
    }

    private int getMedian(ArrayList<Integer> arr){
        Collections.sort(arr);

        int Median = arr.get(arr.size() / 2);

        if(arr.size() % 2 == 0){
            Median = (Median + arr.get(arr.size() / 2 - 1)) / 2;
        }

        return Median;
    }

    private int search(ArrayList<Node> house, Node curt){
        int sum = 0;
        for(Node node : house){
            sum += Math.abs(curt.x - node.x) + Math.abs(curt.y - node.y);
        }
        return sum;
    }

http://www.jiuzhang.com/solutions/build-post-office/
http://www.jianshu.com/p/5395c7fe253f
这道题的要点就是distance可以直接用 x1-x2 + y1-y2求得,所以并不用搜索。做法还是先把所有房子存在一个数组里,然后对于每一个点,遍历房子数组,求total distance即可。
在该题设中,因为房子并不会充当一个阻碍物,所以并不需要用 BFS 等算法来计算最短路径,简单地计算两个格子之间在网格上的曼哈顿距离(Manhattan distance)就好了,即
d(P,Q)=|P.xQ.x|+|P.yQ.y|
最先想到的就是暴力算法:穷举网格上的每一个空地,并计算所有房子到它的距离,最后取最小的一个即可。实现起来就是几个嵌套循环,就此略过。最糟糕的情况下时间复杂度为O(m2n2)
如果我们进一步观察,可以发现,若我们在同一行上移动,所有房子(H)到该行(r)的垂直距离(Y 轴方向)不变,其和也因此不变,即 abs(H(i).yr) 不变。同理,对于每一列也是如此。在同一列上移动,所有房子到该列的水平距离之和也不变。
充分利用上面的观察,我们就可以提出一个更好的算法,即先算出所有房子到每一行的距离之和以及每一列的距离之和,最后在网格上就可以很快的算出所有房子到某点的距离之和了。
想要算出所有房子到每一行或每一列的距离之和,我们可以进一步抽象,把问题转换成一维上的问题。以到每一行的距离之和为例。首先很直观就可以发现,对于任意两行上的点而言,其垂直距离都是固定不变的。于是我们可以进行水平方向的压缩(不需要水平坐标的信息了),即统计出每一行上的房子数目。而后,问题就变成了,在这个一维的线上算出所有点到任意一点的距离之和。利用前缀和(prefix sum),我们可以在O(n)的时间里解决。具体思路就是先从左边扫一遍,记录 [0,i) 范围内的点到 i 的距离之和,又是一个简单的动态规划了,其状态转移方程为
1
prefixCost[i] = prefixCost[i - 1] + prefixSum[i - 1]
其中,prefixSum[i]记录范围 [0,i] 之间点的个数。
类似的,再从右边扫一遍,记录 (i,n1] 范围内的点到 i 的距离之和。最后把左右结果相加即可。
int shortestDistance(vector<vector<int>>& grid) {
int row = grid.size();
if (row == 0)
return -1;
int col = grid[0].size();
if (col == 0)
return -1;
vector<int> rowSum(row, 0);
vector<int> colSum(col, 0);
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
if (grid[i][j] == 1) {
rowSum[i]++;
colSum[j]++;
}
vector<int> rowCost(row, 0);
vector<int> colCost(col, 0);
calculateCost(rowSum, row, rowCost);
calculateCost(colSum, col, colCost);
int minCost = INT_MAX;
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
if (grid[i][j] == 0)
minCost = min(minCost, rowCost[i] + colCost[j]);
if (minCost == INT_MAX)
return -1;
return minCost;
}
void calculateCost(vector<int>& nums, int n, vector<int>& cost) {
vector<int> prefixSum(n, 0);
vector<int> prefixCost(n, 0);
// calculate forward cost - from [0,i) to i
prefixSum[0] = nums[0];
for (int i = 1; i < n; ++i)
prefixSum[i] = prefixSum[i - 1] + nums[i];
prefixCost[0] = 0;
for (int i = 1; i < n; ++i)
prefixCost[i] = prefixCost[i - 1] + prefixSum[i - 1];
// add up forward cost
for (int i = 0; i < n; ++i)
cost[i] = prefixCost[i];
// calculate backward cost - from (i, n) to i
prefixSum[n - 1] = nums[n - 1];
for (int i = n - 2; i >= 0; --i)
prefixSum[i] = prefixSum[i + 1] + nums[i];
prefixCost[n - 1] = 0;
for (int i = n - 2; i >= 0; --i)
prefixCost[i] = prefixCost[i + 1] + prefixSum[i + 1];
// add up backward cost
for (int i = n - 1; i >= 0; --i)
cost[i] += prefixCost[i];
}

1. 因为这个题目要求无解的时候返回 -1 ,那么我们就先想一下无解的情况。

(1)网格不存在,即行数为0或者列数为0;
(2)网格存在,但是没有地方修,也就是没有空地。
 
之后就要开始要想如何解决这个问题了。

2. 题目是要求所有的房子到某一空地的最小曼哈顿距离和,那我们就有一个朴素的想法,直接枚举所有的空地,求出所有的房子到该空地的曼哈顿距离和,从这些距离和中选取最小的一个即可。

(ps:曼哈顿距离:dis=|x2-x1|+|y2-y1|)

伪代码:
接下来就是改进这个朴素的做法。
3. 观察上述伪代码,显然求所有的房子到某一点的曼哈顿距离和是可以通过预处理实现O(1)询问的。

这里就要先提到有关曼哈顿距离的一个常用技巧了:将曼哈顿距离拆分成 X 轴距离与 Y 轴距离。

设两个点:(x1,y1)、(x2,y2)
曼哈顿距离:dis=|x2-x1|+|y2-y1|
根据上面这个式子,我们就可以把求两个点的曼哈顿距离拆分成求两个点在 X 轴上的距离与求两个点在 Y 轴上的距离。
有了这个拆分,就有了预处理的基础。 
3. 观察上述伪代码,显然求所有的房子到某一点的曼哈顿距离和是可以通过预处理实现O(1)询问的。

这里就要先提到有关曼哈顿距离的一个常用技巧了:将曼哈顿距离拆分成 X 轴距离与 Y 轴距离。

设两个点:(x1,y1)、(x2,y2)
曼哈顿距离:dis=|x2-x1|+|y2-y1|
根据上面这个式子,我们就可以把求两个点的曼哈顿距离拆分成求两个点在 X 轴上的距离与求两个点在 Y 轴上的距离。
有了这个拆分,就有了预处理的基础。 

4. 我们现在以对 X 轴距离做预处理为例进行讲解。

我们先预处理出一个rowSum数组,rowSum[i]记录第 i 行一共有几个房子。

那么对于一个点(i,j),从第 0 。。。i 行的所有房子到该点的 X 轴距离和即等同于从第0。。。i 行的所有房子到第 i 行的 X 轴距离和。

用prefixSum1[i]表示从第0。。。i 行的所有房子到第 i 行的一共有多少房子;
用prefixSum2[i]表示从第0。。。i 行的所有房子到第 i 行的X 轴距离和,即得到下式:


根据推导的式子,prefixsum1与prefixsum2都可以通过O(row)的预处理得到。

这样我们就得到了从第0。。。i 行的所有房子到第 i 行的 X 轴距离和。

同理,还可以通过 O(row) 的预处理得到从第 i 。。。n - 1 行的所有房子到第 i 行的 X 轴距离和。

将以上的两个预处理的值相加,即可得到:所有的房子到第 i 行的距离和,将其记为ansRow[i]。

综上,我们就可以通过O(row)的预处理得到所有房子到某一 行的距离和,并记录在ansRow[] 数组里。

5. 通过与第四点相同的思路,我们可以通过一个O(column)的预处理得到所有房子到某一列的距离和,并记录在ansColumn[] 数组里。

于是,所有房子到某一点(i,j)的曼哈顿距离和即为:ansRow[i] + ansColumn[j]。
代码的总体复杂度就下降到了O(row*column)。

如果这道题能够用bfs方法写出来可以达到hire的程度。如果能够优化,想到预处理的方法那么就可以拿到strong hire.
    public int shortestDistance(int[][] grid) {
        // Write your code here
        int row = grid.length, column = grid[0].length;
        if(row == 0 || column == 0 || !haveZero(grid,row,column)) {
         return -1;
        }

        int[] rowSum = new int[row];
        int[] columnSum = new int[column]; 
        for(int i = 0; i < row; i++)
         for(int j = 0; j < column; j++)
          if(grid[i][j] == 1) {
           rowSum[i]++;
           columnSum[j]++;
          }

        int[] ansRow = new int[row];
        int[] ansColumn = new int[column];
        getSumDistance(rowSum,row,ansRow);
        getSumDistance(columnSum,column,ansColumn);

        int ans = Integer.MAX_VALUE;
        for(int i = 0; i < row; i++)
         for(int j = 0; j < column; j++)
          if(grid[i][j] == 0 && ans > ansRow[i] + ansColumn[j]) {
           ans = ansRow[i] + ansColumn[j];
          }
        return ans;
    }

    void getSumDistance(int[] a,int n,int[] ans) {
     int[] prefixSum1 = new int[n];
     int[] prefixSum2 = new int[n];
     /*
     第一阶段,处理前缀。
     prefixSum1记录数组 a 的前缀和,即:prefixSum1[i]=a[0]+a[1]+..+a[i].
     prefixSum2记录数组 prefixSum1 前缀和,prefixSum2即为前 i 个点到第 i 个点的代价和。
     */
     prefixSum1[0] = a[0];
     for(int i = 1; i < n; i++) {
      prefixSum1[i] = prefixSum1[i - 1] + a[i];
     }
     prefixSum2[0] = 0;
     for(int i = 1; i < n; i++) {
      prefixSum2[i] = prefixSum2[i - 1] + prefixSum1[i - 1];
      }

      for(int i = 0; i < n; i++) {
       ans[i] = prefixSum2[i];
      }

     /*
     第二阶段,处理后缀。
     prefixSum1记录数组 a 的后缀和,即:prefixSum1[i]=a[n-1]+a[n-2]+..+a[i].
     prefixSum2记录数组 prefixSum1 的后缀和,prefixSum2即为 i 之后的点到第 i 个点的代价和。
     */
     prefixSum1[n - 1] = a[n - 1];
     for(int i = n - 2; i >= 0; i--) {
      prefixSum1[i] = prefixSum1[i + 1] + a[i];
     }
     prefixSum2[n - 1] =0;
     for(int i = n - 2; i >= 0; i--) {
      prefixSum2[i] = prefixSum2[i + 1] + prefixSum1[i + 1];
      }

      for(int i = 0; i < n; i++) {
       ans[i] += prefixSum2[i];
      }

      /*
      ans[i] 即为a数组中所有点到第 i 点的代价和
      */
    }

    boolean haveZero(int[][] grid, int row, int column) {
     for(int i = 0; i < row; i++) {
      for(int j = 0; j < column; j++){
       if(grid[i][j] == 0) {
        return true;
       }
      }
     }
     return false;
    }
-Not efficient
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return -1;
        ArrayList<Node> house = new ArrayList<>();
        ArrayList<Node> empty = new ArrayList<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    house.add(new Node(i, j));
                }
                else {
                    empty.add(new Node(i, j));
                }
            }
        }
        if (empty.size() == 0) return -1;
        int min = Integer.MAX_VALUE;
        for (Node node: empty) {
            min = Math.min(min, helper(house, node));
        }
        return min;
    }
    private int helper(ArrayList<Node> house, Node node) {
        int dist = 0;
        for (Node cur: house) {
            dist += Math.abs(cur.x - node.x) + Math.abs(cur.y - node.y);
        }
        return dist;
    }
    int shortestDistance(vector<vector<int>>& grid) {
        // Write your code here
        if(grid.empty() || grid[0].empty()) return 0;
        int row = grid.size(), col = grid[0].size();

        vector<pair<int, int>> houses;
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(grid[i][j] == 1){
                    houses.push_back({i, j});
                }
            }
        }
        int ret = INT_MAX;
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(grid[i][j] == 0){
                    int dis = 0;
                    for(int k=0; k<houses.size(); k++){
                        dis += calculate(i, j, houses[k]);
                    }
                    ret = min(ret, dis);
                }
            }
        }
        return ret;
    }

    int calculate(int i, int j, pair<int, int> p){
        return abs(i-p.first) + abs(j-p.second);
    }

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts