Best Meeting Point 最佳见面点

A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

For example, given three people living at (0,0), (0,4), and (2,2):

1 - 0 - 0 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0

The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.

解题思路:

首先,Manhattan Distance 的合为 sum(distance(p1, p2)) = sum(|p2.x - p1.x| + |p2.y - p1.y|)= sum(|p2.x - p1.x|)+sum(|p2.y - p1.y|). 也就是说, 可以分别计算x和y的合, 然后加起来.

其次, 我们需要把2d的grid变成1d, 这里的窍门是, 我们可以证明, 所求的点, 就在其中某点的x或者y的坐标轴上. 所以, 而这点, 必然是1d下的median(一维的最小点必在median点)

public int minTotalDistance(int[][] grid) {
        ArrayList<Integer> r = new ArrayList<Integer>();
        ArrayList<Integer> l = new ArrayList<Integer>();
        //按行获取点
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1)
                    r.add(i);
            }
        }
        //按列获取点,这样保证r,l中的元素的排序的
        for(int j = 0; j < grid[0].length; j++){
            for(int i = 0; i < grid.length; i++){
                if(grid[i][j] == 1)
                    l.add(j);
            }
        }
        return min(r)+min(l);
    }

    public int min(ArrayList<Integer> ary) {
        int i = 0;
        int j = ary.size()-1;
        int sum = 0;
        while(i < j){
            sum += (ary.get(j) -ary.get(i));
            i++;
            j--;
        }
        return sum;
    }

References:

1 Best Meeting Place

2 Best Meeting Point分析

results matching ""

    No results matching ""