Question

I found a code which was very useful for me in implementing A*. but I face one problem. I need to calculate Manhattan distance, I try to implement one but it's not working. this code provide the calculation for Euclidean distance.

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));
    }

the code used c#. thank you very much.

Was it helpful?

Solution

Manhattan distance between A and B (a.k.a L1-norm) is

Sum(abs(a[i] - b[i]))

When Euclidian one between A and B (a.k.a L2-norm) is

Sqrt(Sum((a[i] - b[i])**2))

where a[i], b[i] are corresponding coordinates of A and B points. So the code could be

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top