Move in infinite grid
Problem:
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 from 0,0
Idea is to reach to ith position and from there reach to next.
To reach ith position we need to check with max (i,j) as we can move diagonally with 1 move and from that position (i,i) we can go to (i,j) in j moves.
Code:
public int coverPoints(ArrayList<Integer> A, ArrayList<Integer> B) {
int i=0,j=0;
int step=0;
for(int k=1;k<A.size();++k)
{
step+=Math.max(Math.abs(A.get(k)-A.get(k-1)),Math.abs(B.get(k)-B.get(k-1)));
}
return step;
}
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 from 0,0
Idea is to reach to ith position and from there reach to next.
To reach ith position we need to check with max (i,j) as we can move diagonally with 1 move and from that position (i,i) we can go to (i,j) in j moves.
Code:
public int coverPoints(ArrayList<Integer> A, ArrayList<Integer> B) {
int i=0,j=0;
int step=0;
for(int k=1;k<A.size();++k)
{
step+=Math.max(Math.abs(A.get(k)-A.get(k-1)),Math.abs(B.get(k)-B.get(k-1)));
}
return step;
}
0 Comments:
Post a Comment