Calculate the Manhattan Distance between two cells of given 2D array
Last Updated :
06 Jan, 2022
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++
#include <bits/stdc++.h>
using namespace std;
int manhattanDist( int M, int N, int X1,
int Y1, int X2, int Y2)
{
int dist = abs (X2 - X1) + abs (Y2 - Y1);
return dist;
}
int main()
{
int M = 5, N = 5;
int X1 = 1, Y1 = 2;
int X2 = 3, Y2 = 3;
cout << manhattanDist(M, N, X1, Y1, X2, Y2);
return 0;
}
|
Java
class GFG
{
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;
}
public static void main(String args[])
{
int M = 5 , N = 5 ;
int X1 = 1 , Y1 = 2 ;
int X2 = 3 , Y2 = 3 ;
System.out.println(manhattanDist(M, N, X1, Y1, X2, Y2));
}
}
|
Python3
import math as Math
def manhattanDist(M, N, X1, Y1, X2, Y2):
dist = Math.fabs(X2 - X1) + Math.fabs(Y2 - Y1)
return ( int )(dist)
M = 5
N = 5
X1 = 1
Y1 = 2
X2 = 3
Y2 = 3
print (manhattanDist(M, N, X1, Y1, X2, Y2))
|
C#
using System;
class GFG {
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;
}
public static void Main()
{
int M = 5, N = 5;
int X1 = 1, Y1 = 2;
int X2 = 3, Y2 = 3;
Console.WriteLine(
manhattanDist(M, N, X1, Y1, X2, Y2));
}
}
|
Javascript
<script>
function manhattanDist(M, N, X1,
Y1, X2, Y2) {
let dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1);
return dist;
}
let M = 5, N = 5;
let X1 = 1, Y1 = 2;
let X2 = 3, Y2 = 3;
document.write(manhattanDist(M, N, X1, Y1, X2, Y2));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...