pathfinding between two points in csharp

Here is a basic example of using the A* algorithm to find the shortest path between two points in a grid. This code assumes that the grid is represented as a two-dimensional array of integers, where 0 represents an empty space and any positive integer represents an obstacle.

main.cs
using System;
using System.Collections.Generic;

public class Node
{
    public int x;
    public int y;
    public int gScore;
    public int fScore;
    public Node cameFrom;

    public Node(int x_, int y_)
    {
        x = x_;
        y = y_;
        gScore = int.MaxValue;
        fScore = int.MaxValue;
        cameFrom = null;
    }
}

public static class AStarPathfinding
{
    public static List<Node> FindPath(int[,] grid, Node start, Node end)
    {
        int width = grid.GetLength(0);
        int height = grid.GetLength(1);

        List<Node> openSet = new List<Node>();
        openSet.Add(start);

        Dictionary<Node, int> gScores = new Dictionary<Node, int>();
        gScores[start] = 0;

        Dictionary<Node, int> fScores = new Dictionary<Node, int>();
        fScores[start] = HeuristicCostEstimate(start, end);

        while (openSet.Count > 0)
        {
            Node current = GetLowestFScoreNode(openSet, fScores);

            if (current == end)
            {
                return ReconstructPath(end);
            }

            openSet.Remove(current);

            List<Node> neighbors = GetNeighbors(grid, current, width, height);

            foreach (Node neighbor in neighbors)
            {
                int tentativeGScore = gScores[current] + 1;

                if (tentativeGScore < gScores.GetValueOrDefault(neighbor, int.MaxValue))
                {
                    neighbor.cameFrom = current;
                    gScores[neighbor] = tentativeGScore;
                    fScores[neighbor] = tentativeGScore + HeuristicCostEstimate(neighbor, end);

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }
                }
            }
        }

        return null;
    }

    private static int HeuristicCostEstimate(Node start, Node end)
    {
        int dx = Math.Abs(start.x - end.x);
        int dy = Math.Abs(start.y - end.y);

        return dx + dy;
    }

    private static List<Node> ReconstructPath(Node current)
    {
        List<Node> path = new List<Node>();
        path.Add(current);

        while (current.cameFrom != null)
        {
            current = current.cameFrom;
            path.Add(current);
        }

        path.Reverse();
        return path;
    }

    private static Node GetLowestFScoreNode(List<Node> nodes, Dictionary<Node, int> fScores)
    {
        Node lowestNode = nodes[0];

        for (int i = 1; i < nodes.Count; i++)
        {
            if (fScores.GetValueOrDefault(nodes[i], int.MaxValue) < fScores.GetValueOrDefault(lowestNode, int.MaxValue))
            {
                lowestNode = nodes[i];
            }
        }

        return lowestNode;
    }

    private static List<Node> GetNeighbors(int[,] grid, Node node, int width, int height)
    {
        List<Node> neighbors = new List<Node>();

        if (node.x > 0 && grid[node.x - 1, node.y] != 1) // left
        {
            neighbors.Add(new Node(node.x - 1, node.y));
        }

        if (node.y > 0 && grid[node.x, node.y - 1] != 1) // up
        {
            neighbors.Add(new Node(node.x, node.y - 1));
        }

        if (node.x < width - 1 && grid[node.x + 1, node.y] != 1) // right
        {
            neighbors.Add(new Node(node.x + 1, node.y));
        }

        if (node.y < height - 1 && grid[node.x, node.y + 1] != 1) // down
        {
            neighbors.Add(new Node(node.x, node.y + 1));
        }

        return neighbors;
    }
}
3539 chars
137 lines

To use this code, you can call the FindPath method and pass in the grid, start node, and end node. The method will return a list of nodes representing the shortest path from the start node to the end node. If no path can be found, the method will return null.

main.cs
int[,] grid = new int[,]
{
    { 0, 0, 0, 0, 0 },
    { 0, 1, 1, 1, 0 },
    { 0, 0, 0, 0, 0 },
    { 0, 1, 1, 1, 0 },
    { 0, 0, 0, 0, 0 }
};

Node start = new Node(0, 0);
Node end = new Node(4, 4);

List<Node> path = AStarPathfinding.FindPath(grid, start, end);

if (path == null)
{
    Console.WriteLine("No path found.");
}
else
{
    foreach (Node node in path)
    {
        Console.Write($"({node.x}, {node.y}) ");
    }
}
431 chars
26 lines

gistlibby LogSnag