★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xynpdxro-ku.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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|
.git
For example, given three people living at (0,0)
, (0,4)
, and (2,2)
:github
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:app
兩個或兩個以上的人組成的一個小組,他們想要知足並儘可能減小總的旅行距離。您將獲得一個值爲0或1的二維網格,其中每一個1標記組中某我的的家。使用曼哈頓距離計算距離,其中距離(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.ide
例如,假設有三我的生活在(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。this
提示:idea
首先試着用一維來解決它。這個解決方案如何適用於二維狀況?spa
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