★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10692610.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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.
Hint:
- Try to solve it in one dimension first. How can this solution apply to the two dimension case?
两个或两个以上的人组成的一个小组,他们想要满足并尽量减少总的旅行距离。您将得到一个值为0或1的二维网格,其中每个1标记组中某个人的家。使用曼哈顿距离计算距离,其中距离(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
例如,假设有三个人生活在(0,0)
, (0,4)
和(2,2)
之间:
1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0
点(0,2)是一个理想的汇合点,因为2+2+2=6的总行驶距离是最小的。所以返回6。
提示:
首先试着用一维来解决它。这个解决方案如何适用于二维情况?
Solution:
1 class Solution { 2 func minTotalDistance(_ grid:inout [[Int]]) -> Int { 3 var rows:[Int] = [Int]() 4 var cols:[Int] = [Int]() 5 for i in 0..<grid.count 6 { 7 for j in 0..<grid[i].count 8 { 9 if grid[i][j] == 1 10 { 11 rows.append(i) 12 cols.append(j) 13 } 14 } 15 } 16 cols.sort() 17 var res:Int = 0 18 var i:Int = 0 19 var j:Int = rows.count - 1 20 while(i < j) 21 { 22 res += (rows[j] - rows[i] + cols[j] - cols[i] ) 23 j -= 1 24 i += 1 25 } 26 return res 27 } 28 }
点击:Playground测试
1 var sol = Solution() 2 var grid:[[Int]] = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] 3 print(sol.minTotalDistance(&grid)) 4 //Print 6