leetcode-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:
1 | Input: |
分析
思路1: 采用BFS对每个参会人员进行深度优先搜索。时间复杂度 $O(m^2n^2)$。(Time Limit Exceeded)
思路2: 可以考虑到这道题和317是不一样的,这个题目中没有障碍物的限制。根据曼哈顿可以将行和列分别进行考虑。先将所有参会人员都降维维一行上,计算出最佳的meeting的列,然后再将所有参会人员将为到一列上,计算出最佳的meeting的行。
代码1
1 | // BFS: Time Limit Exceeded |
代码2
1 | // 降维 O(mn) |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/17/leetcode-296/
License: 知识共享署名-非商业性使用 4.0 国际许可协议