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;    }}
原创粉丝点击