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 };

 

posted @ 2020-08-09 11:29  habibah_chang  阅读(150)  评论(0编辑  收藏  举报