以下是一種基本的A*尋路算法的實現示例,可以用于C#語言:
using System;
using System.Collections.Generic;
public class Node
{
public int X { get; set; }
public int Y { get; set; }
public bool IsObstacle { get; set; }
public int G { get; set; } // G值表示起點到該節點的實際代價
public int H { get; set; } // H值表示該節點到目標節點的估計代價
public int F { get { return G + H; } } // F值表示總代價,F = G + H
public Node Parent { get; set; } // 父節點,用于回溯路徑
public Node(int x, int y, bool isObstacle = false)
{
X = x;
Y = y;
IsObstacle = isObstacle;
G = int.MaxValue;
H = 0;
Parent = null;
}
}
public class AStar
{
private int[,] _map; // 地圖,用二維數組表示
private int _width; // 地圖寬度
private int _height; // 地圖高度
public AStar(int[,] map)
{
_map = map;
_width = map.GetLength(0);
_height = map.GetLength(1);
}
public List<Node> FindPath(Node startNode, Node targetNode)
{
List<Node> openList = new List<Node>(); // 開放列表
List<Node> closedList = new List<Node>(); // 關閉列表
startNode.G = 0;
startNode.H = CalculateHeuristic(startNode, targetNode);
openList.Add(startNode);
while (openList.Count > 0)
{
// 從開放列表中選擇F值最小的節點作為當前節點
Node currentNode = FindNodeWithLowestFScore(openList);
openList.Remove(currentNode);
closedList.Add(currentNode);
if (currentNode == targetNode)
{
// 找到路徑,返回路徑上的節點
return GeneratePath(startNode, targetNode);
}
List<Node> neighbors = GetNeighbors(currentNode);
foreach (Node neighbor in neighbors)
{
if (closedList.Contains(neighbor) || neighbor.IsObstacle)
{
// 跳過已在關閉列表中的節點或障礙節點
continue;
}
int tentativeG = currentNode.G + 1; // G值暫時設為當前節點的G值加上從當前節點到相鄰節點的實際代價
if (!openList.Contains(neighbor) || tentativeG < neighbor.G)
{
// 若該相鄰節點不在開放列表中,或者新的G值更小,則更新G、H和父節點
neighbor.G = tentativeG;
neighbor.H = CalculateHeuristic(neighbor, targetNode);
neighbor.Parent = currentNode;
if (!openList.Contains(neighbor))
{
openList.Add(neighbor);
}
}
}
}
// 無法找到路徑,返回空列表
return new List<Node>();
}
private int CalculateHeuristic(Node node, Node targetNode)
{
// 使用曼哈頓距離作為啟發函數(估計代價)
return Math.Abs(node.X - targetNode.X) + Math.Abs(node.Y - targetNode.Y);
}
private Node FindNodeWithLowestFScore(List<Node> nodeList)
{
// 找到F值最小的節點
Node lowestFScoreNode = nodeList[0];
foreach (Node node in nodeList)
{
if (node.F < lowestFScoreNode.F)
{
lowestFScoreNode = node;
}
}
return lowestFScoreNode;
}
private List<Node> GetNeighbors(Node node)
{
List<Node> neighbors = new List<Node>();
int startX = Math.Max(0, node.X - 1);
int endX = Math.Min(_width - 1, node.X + 1);
int startY = Math.Max(0, node.Y - 1);
int endY = Math.Min(_height - 1, node.Y + 1);
for (int x = startX; x <= endX; x++)
{
for (int y = startY; y <= endY; y++)
{
if (x == node.X && y == node.Y)
{