1.原题:

https://leetcode.com/problems/minimum-time-visiting-all-points/

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 arra

翻译:给定一个平面,有n个点,坐标表示为 [xi,yi],你需要求出一个最小的访问时间,你的访问方式必须是以顺序去访问所有的点。每一秒钟你可以水平或者垂直移动一步或者对角移动一步。

此图就是原题的一个示例:

Input : points = [[1,1],[3,4],[-1,0]]

output :7

因为 :[1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]

2.解题思路:

这种简单的最小路径的算法题,思路有很多,最简单的就是贪心算法,因为最无脑。

我们都知道,对角的一步比水平或者垂直移动的一步都要远,所以我们要尽量先走对角,然后实在没有办法的时候再普通的走一步。

那么算法就很明了了:

class Solution {
public:
int minTimeToVisitAllPoints(vector<vector<int>>& points) {  
int ans = 0;   //距离的绝对值
for(int i = 1; i < points.size(); i++) {   
ans += max(abs(points[i][1] - points[i - 1][1]), abs(points[i][0] - points[i - 1][0]));    //求出发点和目的点的xy值的差,比如例子里,x为3-1=2,y为4-1=3。这两个值相同的部分(2) 就是对角的步数,多出来的(1)就是水平或者垂直的移动,因此我们取两者的最大值3,是本次的距离。
}
return ans;
}
};

sub:这里要注意就是 “points.size()” 这个是vector的一个成员函数 .size()其返回的是unsighed int,所以注意不要越界。

最新文章

  1. Java基本数据类型总结
  2. 【python+mysql】在python中调用mysql出问题 ImportError: No module named MySQLdb.constants
  3. sublime jsx 格式化工具
  4. .net工作准备系列--01前言
  5. js 判断鼠标进去方向
  6. c#部分--- 一维数组放到集合中,在从集合中提取输出
  7. 洛谷P1218 [USACO1.5]特殊的质数肋骨 Superprime Rib
  8. oracle11g 重新配置em
  9. redis源码学习
  10. Linux进程间通信——使用数据报套接字
  11. Struts 有哪些经常使用标签库
  12. 在Thinkphp3.2 中使用PHPMailer 发送邮件
  13. Android WifiDirect 学习(三) 一些基础知识和问题
  14. hdu--1800--字典树&amp;&amp;其他
  15. Pivotal开源基于PostgreSQL的数据库Greenplum
  16. SpringBoot之Swagger2的使用
  17. MYSQL 创建数据库SQL
  18. eclipse启动web应用 报错
  19. IP地址和子网划分学习笔记之《IP地址详解》
  20. hive-site.xml

热门文章

  1. 09day vi命令详解
  2. ES5 寄生式继承
  3. 【PAT甲级】1111 Online Map (30分)(dijkstra+路径记录)
  4. SOCV / POCV 模型 (3)
  5. matlab 绘制原始信号的谐波
  6. java.net.URISyntaxException: Illegal character in query at index 147
  7. spark实验(五)--Spark SQL 编程初级实践(1)
  8. Linux格式化数据盘
  9. ZooKeeper下载安装配置-单机版配置
  10. Druid数据源SQL数据库与Spring监控