题目信息
- 平台:LeetCode
- 题目:1266. 访问所有点的最小时间
- 难度:Easy
- 题目链接:Minimum Time Visiting All Points
题目描述
给定一系列平面坐标点,必须按顺序依次访问。每一步可以在一个时间单位内沿横、纵或对角线移动 1 格,求访问所有点所需的最小时间。
初步思路
- 对角线移动可以让 x、y 同时各改变 1;优先走对角线。
- 对剩余的单轴差距再用直走补齐,等价于取 max(|dx|, |dy|)。
算法分析
- 核心:相邻两点最短时间 =
max(|dx|, |dy|)。 - 技巧:对每一对相邻点直接累加即可。
- 时间复杂度:O(n)
- 空间复杂度:O(1)
代码实现(C++)
cpp
#include <cmath>
#include <vector>
using namespace std;
class Solution {
public:
int minTimeToVisitAllPoints(vector<vector<int>> &points) {
int res = 0;
if(points.size() == 0)return 0;
auto& p = points[0];
for (int i = 1; i < points.size(); ++i) {
auto &q = points[i];
res += max(abs(p[0] - q[0]), abs(p[1] - q[1])); // 切比雪夫距离
p = q;
}
return res;
}
};
测试用例
| 输入 | 输出 | 说明 |
|---|---|---|
| points = [[1,1],[3,4],[-1,0]] | 7 | (1,1)->(3,4)用3步,(3,4)->(-1,0)用4步 |
| points = [[3,2],[-2,2]] | 5 | 仅一段移动,max( |
| points = [[0,0],[0,0]] | 0 | 同一点无需移动 |
总结与反思
- 允许对角移动时,两点最短步数就是切比雪夫距离。
- 题目结构简单,重点是观察到"同时走 x 与 y"能省步数。