[Locked] Best Meeting Point
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.
分析:
第一反应就是求二维平面上的距离最优值;由于是曼哈顿距离,所以x维和y维可以分开求最小,最终结果也会最小,这样转化成了一维轴上绝对值之和最小,中学学过嘛,画图可知。
解法:
找到x轴上所有为1的点,然后从外到内依次两两index求差,这些差的总和为x轴上的最小值;y轴上也做同样的操作得到y轴最小值。两轴上的最小值之和为最小曼哈顿距离。时间复杂度为m*n,空间复杂度为1的个数。
代码:
int minDist(vector<vector<int> > v) { deque<int> inum, jnum; int dist = 0; for(int i = 0; i < v.size(); i++) { for(int j = 0; j < v[0].size(); j++) { if(v[i][j]) inum.push_back(i); } } while(inum.size() >= 2) { dist += inum.back() - inum.front(); inum.pop_front(); inum.pop_back(); } for(int j = 0; j < v[0].size(); j++) { for(int i = 0; i < v.size(); i++) { if(v[i][j]) jnum.push_back(j); } } while(jnum.size() >= 2) { dist += jnum.back() - jnum.front(); jnum.pop_front(); jnum.pop_back(); } return dist; }