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 && 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