.net 编写A*算法

  • Post author:
  • Post category:其他


A* 算法是一种用于在图形或网格中搜索最优路径的算法。你可以在 .NET 中使用这种算法来找到两个给定点之间的最短路径。

以下是用 C# 编写 A* 算法的简单示例:

“` using System; using System.Collections.Generic;

public class AStar { private class Node : IComparable

{ public int X { get; set; } public int Y { get; set; } public int G { get; set; } public int H { get; set; } public Node Parent { get; set; }

publicint CompareTo(Node other)
    {
        int f = G + H;
        int of = other.G + other.H;
        if (f > of)
        {
            return 1;
        }
        else if (f < of)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
}

private static int Heuristic(int x, int y, int goalX, int goalY)
{
    int dx = Math.Abs(x - goalX);
    int dy = Math.Abs(y - goalY);
    return dx + dy;
}

public static List<Node> FindPath(int startX, int startY, int goalX, int goalY, bool[,] blocked)
{
    List<Node> open = new List<Node>();
    List<Node> closed = new List<Node>();
    Node start = new Node { X = startX, Y = startY };
    Node goal = new Node { X = goalX, Y = goalY };
    open.Add(start);
    while (open.Count > 0)
    {
        Node current = open[0];
        for (int i = 1; i < open.Count; i++)
        {
            if (open[i].CompareTo(current) < 0)
            {
                current = open[i];
            }
        }
        open.Remove(current);
        closed.Add(current);
        if (current.X == goal.X &amp;&amp; current.Y == goal.Y)
        {
            List<Node> path = new List<Node>();
            while (current.Parent != null)
            {
                path.Add(current);
                current = current.Parent;
            }
            path.Reverse();
            return path;
        }
        foreach (Node neighbor in GetNeighbors(current, goal, blocked))
        {
            if (closed.Contains(neighbor))
            {
                continue;
            }
            int g = current.G + 1;
            bool newPath = false;
            if (!open.Contains(neighbor))
            {
                open



版权声明:本文为weixin_35752645原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。