Algorithm-Arrays-1
来源:互联网 发布:矩阵行列式计算器 编辑:程序博客网 时间:2024/06/02 06:03
1.问题Min steps in infinite grid
You are in an infinite 2D grid where you can move in any of the 8 directions :
(x,y) to (x+1, y), (x - 1, y), (x, y+1), (x, y-1), (x-1, y-1),(x+1,y+1), (x-1,y+1), (x+1,y-1)
You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point.
Example :
Input : [(0, 0), (1, 1), (1, 2)]
Output : 2
即:给定一个二维网格中一个点,可以向该点出发的8个方向移动。输入为所需要经过的点的坐标,要求输出为所需经过的步数。
2.思路
Note that because the order of covering the points is already defined, the problem just reduces to figuring out the way to calculate the distance between 2 points (A, B) and (C, D).
Note that what only matters is X = abs(A-C) and Y = abs(B-D).
While X and Y are positive, you will move along the diagonal and X and Y would both reduce by 1.
When one of them becomes 0, you would move so that in each step the remaining number reduces by 1.
In other words, the total number of steps would correspond to max(X, Y).
即:该问题可以归结到求2点之间的距离上来。如p(A,B),q(C,D)
distance = max(abs(A-C),abs(B-D)).
3.代码
java版本实现:
public class Solution { // X and Y co-ordinates of the points in order. // Each point is represented by (X.get(i), Y.get(i)) public int coverPoints(ArrayList<Integer> X, ArrayList<Integer> Y) { int result = 0; for(int i=0; i<X.size()-1; i++){ result += Math.max(Math.abs(X.get(i+1)-X.get(i)),Math.abs(Y.get(i+1)-Y.get(i))); } return result; }}
- Algorithm-Arrays-1
- Algorithm-Arrays-2
- Algorithm-Arrays-8 Noble Integer
- Algorithm Arrays-3 Max Sum Contiguous Subarray
- Algorithm-Arrays-6 Kth pascal triangle
- Algorithm-Arrays-7 Diagonals 对角线输出
- Algorithm(1)
- 算法库algorithm-1-algorithm
- 【LeetCode-Algorithm】【4-Median of Two Sorted Arrays】【Python】
- Algorithm-Arrays-4 最大绝对距离Max Absolute Difference
- Algorithm-Arrays-5 Repeat and Missing Number Array
- Algorithm之路四:Median of Two Sorted Arrays
- string algorithm 1
- Algorithm in Python(1)
- algorithm—for_each() (1)
- PageRank Algorithm (1)
- 《Algorithm》读书笔记-1
- algorithm analysis 开坑1
- mongo权限认证
- 关于计划任务3
- iOS指纹解锁,几行代码解决,特简单
- MySQL 5.7 新特性 JSON 的创建,插入,查询,更新
- php中日志文件防止并发写入
- Algorithm-Arrays-1
- Mycat 配置
- 7种垃圾收集器
- kafka 数据可靠性深度解读
- Swift: 消除警告- All interface orientations must be supported unless the app requires full screen
- kafka
- ArcSDE版本压缩(Compress)(2)
- hittest方法的底层实现与应用
- 卷积神经网络基础卷积层和池化层学习#####好好好