.net 编写A*算法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值