Calculate the Manhattan Distance between two cells of given 2D array (original) (raw)
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.
C++ `
// C++ code to implement above approach #include <bits/stdc++.h> using namespace std;
// Code to calculate Manhattan distance int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = abs(X2 - X1) + abs(Y2 - Y1); return dist; }
// Driver code int main() { // Define size of 2-D array int M = 5, N = 5;
// First point
int X1 = 1, Y1 = 2;
// Second point
int X2 = 3, Y2 = 3;
cout << manhattanDist(M, N, X1, Y1, X2, Y2);
return 0;}
Java
// java code to implement above approach
class GFG {
// Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1); return dist; }
// Driver code public static void main(String args[]) {
// Define size of 2-D array
int M = 5, N = 5;
// First point
int X1 = 1, Y1 = 2;
// Second point
int X2 = 3, Y2 = 3;
System.out.println(manhattanDist(M, N, X1, Y1, X2, Y2));} }
// This code is contributed by gfgking.
Python3
Python code for the above approach
import math as Math
Code to calculate Manhattan distance
def manhattanDist(M, N, X1, Y1, X2, Y2): dist = Math.fabs(X2 - X1) + Math.fabs(Y2 - Y1) return (int)(dist)
Driver code
Define size of 2-D array
M = 5 N = 5
First point
X1 = 1 Y1 = 2
Second point
X2 = 3 Y2 = 3
print(manhattanDist(M, N, X1, Y1, X2, Y2))
This code is contributed by Saurabh Jaiswal
C#
// C# code to implement above approach using System; class GFG {
// Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.Abs(X2 - X1) + Math.Abs(Y2 - Y1); return dist; }
// Driver code public static void Main() {
// Define size of 2-D array
int M = 5, N = 5;
// First point
int X1 = 1, Y1 = 2;
// Second point
int X2 = 3, Y2 = 3;
Console.WriteLine(
manhattanDist(M, N, X1, Y1, X2, Y2));} }
// This code is contributed by ukasp.
JavaScript
`
Time Complexity: O(1)
Auxiliary Space: O(1)