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. 

转载于:https://www.cnblogs.com/aprilyang/p/6507928.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值