0

I have a list of Point types in C#. I want to run Dijkstra's algorithm on this list of points where the first entry in the list is the starting location.

Is there a way of doing this using an existing library?

If such library doesn't exist, is there a way of calculating the distance between two points with x and y coordinates. For example, calculate the distance between point A (x coordinate =2, y coordinate = 4) and point B ((x coordinate =9, y coordinate = 7).

I have used the ZedGraph library to build the graph.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jetnor
  • 521
  • 2
  • 11
  • 26
  • 6
    Dijkstra's algo calculates the shortest path in a graph. You appear to have cartesian coordinates. What gives? – Tudor Aug 21 '12 at 15:57
  • 1
    Calculating the distance between 2 points with X and Y coordinates? You mean like √((x1 - x2)² + (y1 - y2)²)`? – Ry- Aug 21 '12 at 16:06
  • @Tudor Hi Tudor, I do have a list of cartasian coordinates each stored in a Point data type. These coordinates represent a graph's edges. I want to find the shortest way to visit all the edges. – Jetnor Aug 21 '12 at 17:11
  • So is there a way of doing what I want to? Thanks, jetnor – Jetnor Aug 21 '12 at 18:58
  • @Jentor, What exactly are you trying to find? what is the size of the graph? – Vitaliy Sep 02 '12 at 18:21

1 Answers1

0

I think you misunderstood, what the Dijkstra algorithm stands for.

For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.

What you need (i think) the lowest distance between two points based on their coordinates.

And the distance between two points can be counted using basic math:

Point p = new Point(4, 5);
Point r = new Point(10, 2);

double distance = Math.Sqrt(Math.Pow(p.X - r.X, 2) + Math.Pow(p.Y - r.Y, 2));

using this knowledge the problem could be solved with two functions like this:

Returns the distance between p and r:

static double distance(Point p, Point r)
{
     return Math.Sqrt(Math.Pow(p.X - r.X, 2) + Math.Pow(p.Y - r.Y, 2));
}

Returns the index of the closest point to the fromIndex th element of the points list:

static int closestPoint(List<Point> points, int fromIndex)
{
    Point start = points[fromIndex];
    int resultIndex = 0;

    for (int i = 1; i < points.Count; i++)
    {
        if (fromIndex == i) 
            continue;

        Point current = points[i];

        if (distance(start, current) < distance(start, points[resultIndex]))
            resultIndex = i;
    }

    return resultIndex;
}

I'm really sorry, if i misunderstood you!

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89