Search code examples
c#wpfalgorithmgrid-layout

Closest path between points on grid


I have grid dimension 2000x2000. I have some points stored on grid and I want to connect some of them, but connection need to be closest path from one to another. I have :

private static readonly Dictionary<double,Point> ExistingPoints = new Dictionary<double, Point>(); private static Point[,] gridMatrix = new Point[200, 200];

where ExistingPoints is dictionary of points that are placed on grid and gridMatrix contains same points from dictionary, but his row and column are x and y from point divided by 10 so it can be represented on grid.

So how can I find closest path from one point to another?

EDIT

Path can only go on grid, meaning it can go on lines only, it can't be straight line, so when I need to go up/ down/ left/ right it need to be on 90 degrees


Solution

  • Okey as we said in the comments I would do this:

    List<Point> path = new List<Point>();
    Point startingPoint = new Point(1000, 1000);
    Point targetPoint = new Point(500, 500);
    Point currentPos = startingPoint;
    
    //Level in Y
    while (currentPos.Y != targetPoint.Y)
    {
         path.Add(new Point(currentPos.X, currentPos.Y);
         currentPos.Y += (currentPos.Y > targetPoint.Y ? -1 : 1);
    }
    //Level in X
    while(currentPos.X != targetPoint.X)
    {
         path.Add(new Point(currentPos.X, currentPos.Y);
         currentPos.X += (currentPos.X > targetPoint.X ? -1 : 1);
    }
    
    //Draw the lines in steps
    for (int i = 0; i < path.Count()-1; i++)
    {
         DrawLineBetween(path[i], path[i + 1]);
    }
    DrawLineBetween(path.Last(), targetPoint);
    

    I did not test the code but it compiles and should work in theory. The Method DrawLineBetweenstill has to be implemented of course but I guess you have something in place here.

    You could, of course, combine the X and Y leveling in one loop and then go in a "stair" pattern.