[Swift]LeetCode296. 最佳开会地点 $ Best Meeting Point

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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:

  1. 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

 

转载于:https://www.cnblogs.com/strengthen/p/10692610.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值