1. 程式人生 > 實用技巧 >1266. Minimum Time Visiting All Points

1266. Minimum Time Visiting All Points

問題:

給出一組座標點,飛機按照順序,以座標點為目標進行飛行,

移動一個單位(水平,垂直,對角線),花費 1 秒鐘。

求總共花費時間。

Example 1:
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]   
Time from [1,1] to [3,4] = 3 seconds 
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds

Example 2:
Input: points = [[3,2],[-2,2]]
Output: 5
 

Constraints:
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000

解法:

任意兩點之間的 花費最小時間

= max(x座標偏移,y座標偏移)

而這裡,偏移一定為非負整數。因此計算偏移,需用到abs求絕對值。

程式碼參考:

 1 class Solution {
 2 public:
 3     int minTimeToVisitAllPoints(vector<vector<int>>& points) {
 4         int res=0;
 5         for(int i=1; i<points.size(); i++) {
 6             int x_diff = abs(points[i][0
] - points[i-1][0]); 7 int y_diff = abs(points[i][1] - points[i-1][1]); 8 res+=max(x_diff, y_diff); 9 } 10 return res; 11 } 12 };