본문 바로가기

DataStructure/Array

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.

Input :

Given two integer arrays A and B, where A[i] is x coordinate and B[i] is y coordinate of ith point respectively.

Output :

Return an Integer, i.e minimum number of steps.

Example :

Input : [(0, 0), (1, 1), (1, 2)]
Output : 2

It takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2).

This question is intentionally left slightly vague. Clarify the question by trying out a few cases in the “See Expected Output” section.

class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def cover_points(self, A, B):
a_size = len(A)
sum = 0

for i in range(a_size - 1):
diff_x = abs(A[i+1] - A[i])
diff_y = abs(B[i+1] - B[i])
if diff_x >= diff_y:
sum += diff_x
else:
sum += diff_y
return sum

It's easy to solve this problem.

But, I make a mistake because I forget using abs method before submitting my answer.

'DataStructure > Array' 카테고리의 다른 글

Max Sum Contiguous Subarray  (0) 2018.10.16
Add One To Number  (0) 2018.10.15
Left Rotation  (0) 2018.04.19
Dynamic Array  (0) 2018.04.19
2D Array - DS  (0) 2018.04.13