Build Post Office II Lintcode

Given a 2D grid, each cell is either a wall 2, an house 1or 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.

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

Given a grid:

0 1 0 0 0
1 0 0 2 1
0 1 0 0 0

return 8, You can build at (1,1). (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.

 

This problem can use reverse bfs. We can think about a problem in a reverse way. Since house number is much smaller than empty spaces we use house to bfs, which will be more efficient.

public class Solution {
    /**
     * @param grid a 2D grid
     * @return an integer
     */
    
    class Coordinate {
        int x;
        int y;
        Coordinate(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        int n = grid.length;
        int m = grid[0].length;
        int[][] visitedTimes = new int[n][m];
        int[][] steps = new int[n][m];
        ArrayList<Coordinate> houses = new ArrayList<>();
        ArrayList<Coordinate> empty = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 0) {
                    empty.add(new Coordinate(i, j));
                }
                if (grid[i][j] == 1) {
                    houses.add(new Coordinate(i, j));
                }
            }
        }
        
        for (Coordinate house : houses) {
            bfs(grid, house, visitedTimes, steps);
        }
        int min = Integer.MAX_VALUE;
        int houseNumber = houses.size();
        for (Coordinate p: empty) {
            int x = p.x;
            int y = p.y;

            if (visitedTimes[x][y] == houseNumber) {
                if (steps[x][y] != 0 && steps[x][y] < min) {
                    min = steps[x][y];
                }
            }
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }
    public void bfs(int[][] grid, Coordinate point, int[][] visitedTimes, int[][] steps) {
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        Queue<Coordinate> q = new LinkedList<>();
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        q.add(point);
        int step = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            step++;
            for (int i = 0; i < size; i++) {
                Coordinate house = q.poll();
                for (int j = 0; j < 4; j++) {
                    int x = house.x + dx[j];
                    int y = house.y + dy[j];
                    Coordinate nextHouse = new Coordinate(x, y);
                    if (isValid(grid, nextHouse) && !visited[x][y]) {
                        steps[x][y] += step;
                        visitedTimes[x][y]++;
                        q.offer(nextHouse);
                        visited[x][y] = true;
                    }
                }
            }
        }
    }
    private boolean isValid(int[][] grid, Coordinate point) {
        int x = point.x;
        int y = point.y;
        return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] == 0;
    }
}

Notice that we need a matrix to record which one is visited and how many times there are. And another matrix to record how many stepts are needed to get that point. In the end, find one point that is visited the number of house times and have the minimum steps.

It is a hard problem but once have known the pattern, it is easy to solve these bfs problems. 

posted @ 2017-03-06 05:38  璨璨要好好学习  阅读(889)  评论(0编辑  收藏  举报