我找到了一段对我实现 A* 非常有用的代码。但我面临一个问题。 我需要计算曼哈顿距离,我尝试实现一个但它不起作用。此代码提供欧氏距离的计算。
public Node(Node parentNode, Node goalNode, int gCost,int x, int y)
{
this.parentNode = parentNode;
this._goalNode = goalNode;
this.gCost = gCost;
this.x=x;
this.y=y;
InitNode();
}
private void InitNode()
{
this.g = (parentNode!=null)? this.parentNode.g + gCost:gCost;
this.h = (_goalNode!=null)? (int) Euclidean_H():0;
}
private double Euclidean_H()
{
double xd = this.x - this._goalNode .x ;
double yd = this.y - this._goalNode .y ;
return Math.Sqrt((xd*xd) + (yd*yd));
}
代码使用了c#。 非常感谢。
请您参考如下方法:
A 和 B 之间的曼哈顿距离(也称为 L1 范数)是
Sum(abs(a[i] - b[i]))
当 A 和 B 之间的欧几里得之一(又名 L2-范数)是
Sqrt(Sum((a[i] - b[i])**2))
其中a[i],b[i]分别是A点和B点对应的坐标。 所以代码可以是
private double Manhattan_H()
{
double xd = this.x - this._goalNode.x;
double yd = this.y - this._goalNode.y;
return Math.Abs(xd) + Math.Abs(yd);
}
