296. 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|
.
Example:
Input:
1 - 0 - 0 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
Output: 6
Explanation: Given three people living at (0,0), (0,4), and (2,2):
The point (0,2) is an ideal meeting point, as the total travel distance
of 2+2+2=6 is minimal. So return 6.
方法0: bfs, TLE
官方题解: https://leetcode.com/problems/best-meeting-point/solution/
思路:
第一次看到bfs被列为brute force的。这里bfs和317. Shortest Distance from All Buildings中用的思路一样,从所有1出发,计算到每个点的距离。注意这道题中,其实不在乎每一个点上是0还是1,第一路线可以穿越1,第二meeting point可以是某人所在的点。
Complexity
Time complexity: O(m^2 n^2)
Space complexity: O(mn)
方法0: brute force,Manhattan’s distance
思路:
用两个循环计算pairwise的曼哈顿距离。一样tle。
方法1: sort
思路:
首先用一维的情况来举例,best meeting在两点之间始终是两点距离,并且一定不会是两者之外。那么三个点的情况,A____B__C,最佳汇合点一定是 B。四个点时A____B_C___D,在BC之间都一样,以此类推。也就是说首先将这些点排序,用双指针一对一对的计算距离累加,最后剩下一个点可以不用管。推广至二维是一样的,按两个方向排好序,一对一对的取出累加即可。
为什么不用给rows排序?因为是按照rows来push的,本来就排好了。cols是乱序的。
Complexity
Time complexity: O(mnlogmn)
Space complexity: O(mn)
class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
vector<int> rows;
vector<int> cols;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j ++) {
if (grid[i][j]) {
rows.push_back(i);
cols.push_back(j);
}
}
}
sort(cols.begin(), cols.end());
int result = 0, low = 0, high = rows.size() - 1;
while (low < high) {
result += abs(rows[low] - rows[high]) + abs(cols[low] - cols[high]);
low++;
high--;
}
return result;
}
};