Min Steps in Infinite Grid

Tejas M R
1 min readAug 12, 2021

You are in an infinite 2D grid where you can move in any of the 8 directions

(x,y) to 
(x-1, y-1),
(x-1, y) ,
(x-1, y+1),
(x , y-1),
(x , y+1),
(x+1, y-1),
(x+1, y) ,
(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.

Note that I am using C++ for this.

Solution:

The shortest distance you need to travel from one point to another by taking any of the 8 neighboring points of each point is called chessboard distance.

ChessBoardDistance( p1, p2 ) = max( |p1.x-p2.x|, |p1.y-p2.y| ) where p1, p2 are 2d points.

In code, one way to translate this is:

int chessboardDistance( int x1, int y1, int x2, int y2 ) { 
return max( abs(x1-x2), abs(y1-y2) );
}

Based on the way the points are given to you, the solution becomes very easy. One way is:

int minimumDistanceInOrder(vector<int> &A, vector<int> &B) {
int n=A.size(), minimumDistance = 0;
for( int i=0; i<n-1; i++ ) {
minimumDistance += chessboardDistance( A[i], B[i], A[i+1], B[i+1] );
}
return minimumDistance;
}

If you get an array of pairs of integers as input then you can modify the above solution to suit the given format.

--

--

Tejas M R

Tejas M R is a Junior iOS Developer who is also interested in Machine Learning, Data Science, Creative Writing, Cybersecurity and more!