计算给定二维数组的两个单元格之间的曼哈顿距离
给定一个大小为M * N的二维数组和(X 1 , Y 1 )和(X 2 , Y 2 )形式的两个点,其中X 1和X 2代表行, Y 1和Y 2代表列。任务是计算给定点之间的曼哈顿距离。
例子:
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
方法:该方法基于数学观察。两点之间的曼哈顿距离是坐标的绝对差之和。
Manhattan distance = |X1 – X2| + |Y1 – Y2|
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
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
输出
3
时间复杂度: O(1)
辅助空间: O(1)