a* path finding in csharp

Here's an example implementation of the A* algorithm in C#:

main.cs
public class Node
{
    public int x;
    public int y;
    public Node parent;
    public float g;
    public float h;
    public float f;

    public Node(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

public static List<Node> AStar(Node start, Node goal)
{
    var closedSet = new HashSet<Node>();
    var openSet = new HashSet<Node> { start };
    var cameFrom = new Dictionary<Node, Node>();
    var gScore = new Dictionary<Node, float> { [start] = 0 };
    var fScore = new Dictionary<Node, float> { [start] = Heuristic(start, goal) };

    while (openSet.Count > 0)
    {
        var current = openSet.OrderBy(node => fScore[node]).First();

        if (current == goal)
            return ReconstructPath(cameFrom, current);

        openSet.Remove(current);
        closedSet.Add(current);

        foreach (var neighbor in GetNeighbors(current))
        {
            if (closedSet.Contains(neighbor))
                continue;

            float tentative_gScore = gScore[current] + GetDistance(current, neighbor);

            if (!openSet.Contains(neighbor))
                openSet.Add(neighbor);
            else if (tentative_gScore >= gScore[neighbor])
                continue;

            cameFrom[neighbor] = current;
            gScore[neighbor] = tentative_gScore;
            fScore[neighbor] = tentative_gScore + Heuristic(neighbor, goal);
        }
    }

    return new List<Node>();
}

private static List<Node> ReconstructPath(Dictionary<Node, Node> cameFrom, Node current)
{
    var path = new List<Node>();

    while (cameFrom.ContainsKey(current))
    {
        path.Add(current);
        current = cameFrom[current];
    }

    path.Reverse();
    return path;
}

private static float Heuristic(Node a, Node b)
{
    return Math.Abs(a.x - b.x) + Math.Abs(a.y - b.y);
}

private static float GetDistance(Node a, Node b)
{
    return Heuristic(a, b);
}

private static IEnumerable<Node> GetNeighbors(Node node)
{
    yield return new Node(node.x - 1, node.y);
    yield return new Node(node.x + 1, node.y);
    yield return new Node(node.x, node.y - 1);
    yield return new Node(node.x, node.y + 1);
}
2157 chars
87 lines

This implementation assumes that the map/grid of nodes is stored in a 2D array or some other data structure that supports efficient lookup of nodes based on their position. The GetNeighbors method determines the neighbors of a given node, and the Heuristic method calculates the estimated distance between two nodes (used to prioritize nodes to search next). The AStar method returns a list of nodes representing the shortest path from the start node to the goal node.

gistlibby LogSnag