Description
On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.
You can move according to the next rules:
- In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).
- You have to visit the points in the same order as they appear in the array.
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
分析
题目的意思是:给你一个数组,求遍历每一个点所需要的步数,每次一只能走一格,可以斜着走。这里我用最暴力的方法写了一下,发现也能AC,但是速度很慢。后面看了一下别人的实现,发现从一个点走到另一个点的最小步骤是两点的坐标(x,y)差的最大值,即:
max(abs(next_point[0] - point[0]), abs(next_point[1] - point[1]))
如果这个弄懂了,就能写出速度很快的代码,当然下面的代码是我的原创,我希望多一点我的原创代码,所以就分享给大家,没有放速度快的版本。
代码
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
x,y=points[0]
n=len(points)
cnt=0
for i in range(1,n,1):
x1,y1=points[i]
while(x!=x1 or y!=y1):
if(x<x1):
x+=1
elif(x>x1):
x-=1
if(y>y1):
y-=1
elif(y<y1):
y+=1
cnt+=1
return cnt