C#实现曼哈顿距离算法的完整源代码
曼哈顿距离算法(Manhattan distance)是计算两点之间的距离的一种方法,它是指从一个点到另一个点沿着网格线的距离总和。在这篇文章中,我们将使用C#编程语言来实现曼哈顿距离算法。
首先,我们需要定义一个Point结构体来表示一个点的坐标。代码如下:
public struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
接下来,我们编写一个函数来计算两个点之间的曼哈顿距离。代码如下:
public static int ManhattanDistance(Point p1, Point p2)
{
return Math.Abs(p1.x - p2.x) + Math.Abs(p1.y - p2.y);
}
这个函数接受两个Point类型的参数p1和p2,然后返回它们之间的曼哈顿距离。我们使用了Math类中的Abs方法来计算每个方向上的距离,并将它们相加得到总距离。
现在我们可以在主函数中测试这个函数了。例如,如果我们想要计算(0,0)和(3,4)之间的曼哈顿距离,我们可以这样做:
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
int distance = ManhattanDistance(p1, p2);
Console.WriteLine("Manhattan distance between ({0},{1}) and ({2},{3}) is {4}", p1.x,