Min Steps in Infinite Grid - The Coding Shala

Home >> Programming Questions >> Min steps in Infinite grid

Min Steps in Infinite Grid InterviewBit Solution

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), 
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.
Min Steps in Infinite Grid Java Program - The Coding Shala
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).

Solution: (Java)

Try to figure out the distance between two points. lets consider two points A(x1,y1) and B(x2,y2). So distance needs to cover between these two points is a max of x-axis or y-axis.

public class Solution {
    public int coverPoints(ArrayList<Integer> A, ArrayList<Integer> B) {
        int n = A.size();
        int ans = 0;
        for(int i=1;i<n;i++){
           int x = Math.abs(A.get(i)-A.get(i-1));
           int y = Math.abs(B.get(i)-B.get(i-1));
           ans += (x>=y) ? x : y;
        return ans;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala