Minimum steps in Grid

Minimum steps in Grid

 
You are in an infinite 2D grid where you can move in any possible direction.

find the minimum number of steps required to reach to the target (X,Y) coordinates. In this question, it is straight forward assumption that the inception point is (0,0). So, we need to find the minimum number of steps to reach from (0,0) to (X,Y) coordinates.

Here is the solution: 

 



package com.diaryreaders.IB;
public class MinStepsGrid {
static int minStepsGrid(int[][] matrix, int targetX, int targetY) throws Exception {
int m = matrix.length;
int n = matrix[0].length;
if (targetX > m || targetY > n) {
throw new Exception("Invalid coordinates");
}
return Math.max(targetX, targetY);
}
public static void main(String[] args) throws Exception {
int[][] matrix = { { 1, 2, 3, 4, 5 }, 
{ 6, 7, 8, 9, 10 }, 
{ 11, 12, 13, 14, 15 }, 
{ 16, 17, 18, 19, 20 } };
System.out.println(minStepsGrid(matrix,2,4));
}
}


 
Output:

 
Extending question a bit. Now, we need to find minimum steps to traverse the specific path for example from inception (0,0) to (1,1) then from (1,1) to (1,2).
 
Lets see the solution for this.
 



public class MinStepsGrid {
static int minStepsGrid(int[][] matrix, int[] targetX, int[] targetY) throws Exception {
int maxStepsCount = 0 ;
for (int i = 1; i < targetX.length; i++) {
maxStepsCount += Math.max(targetX[i]-targetX[i-1],targetY[i]-targetY[i-1]); 
}
return maxStepsCount;
}
public static void main(String[] args) throws Exception {
int[][] matrix = { 	{ 1, 2, 3, 4, 5 }, 
{ 6, 7, 8, 9, 10 }, 
{ 11, 12, 13, 14, 15 }, 
{ 16, 17, 18, 19, 20 } };
int[] targetX = {0,1,1};
int[] targetY = {0,1,2};
System.out.println(minStepsGrid(matrix,targetX,targetY));
}
}


 
Output:

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON