VOOZH about

URL: https://www.geeksforgeeks.org/dsa/calculate-the-manhattan-distance-between-two-cells-of-given-2d-array/

⇱ Calculate the Manhattan Distance between two cells of given 2D array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Calculate the Manhattan Distance between two cells of given 2D array

Last Updated : 23 Jul, 2025

Given a 2D array of size M * N and two points in the form (X1, Y1) and (X2 , Y2) where X1 and X2 represents the rows and Y1 and Y2 represents the column. The task is to calculate the Manhattan distance between the given points. 

Examples:

Input: M = 5, N = 5, X1 = 1, Y1 = 2, X2 = 3, Y2 = 3
Output: 3
Explanation: As per the definition, the Manhattan the distance is same as sum of the absolute difference of the coordinates.

Input: M = 5, N = 5, X1 = 4, Y1 = 2, X2 = 4, Y2 = 2
Output: 0

Approach: The approach is based on mathematical observation. The Manhattan distance between two points is the sum of absolute difference of the coordinates.

Manhattan distance = |X1 - X2| + |Y1 - Y2|

Below is the implementation of the above approach.

 
 


Output
3

Time Complexity: O(1)
Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: