转自:http://www.cnblogs.com/technology/archive/2011/05/26/2058842.html
地图
二位数组表示地图,其中包含障碍物、起点和终点。
列表
开启列表:等待检查的方格的列表
关闭列表:存放不需要再次检查的方格
公式
F=G+H
G:起点到某方格的移动耗费。
H:某方格到终点的预计耗费,是一直不变的。
寻路步骤
1、将起点存入“开启列表”。
2、寻找起点周围可以到达的方格(离起点最近的方格),将它们放入“开启列表”,并设置它们的父方格为起点。
3、从“开启列表”删除起点,并将起点加入“关闭列表”。
4、从“开启列表”中选择 F值最低 的方格C加入“关闭列表”,并从“开启列表”删除。
5、检查上一步骤加入关闭列表的方格C的所有相邻方格(障碍和关闭列表中的不考虑)。
5.1、如果方格不在开启列表,将其加入开启列表并计算FGH值,设置父方格为C。
5.2、如果方格已经在开启列表中,比较C到它的G值和之前的G值,如果G值更低了,那么更新这个方格的FG值和父方格。
6、继续从开启列表寻找F值最小的,重复上述步骤,直到“开启列表”中出现终点方格。
7、如果开启列表为空了还没有终点出现,说明路径不存在。
路径
每个方格有一个父方格,通过父方格寻回路径。
从终点方格开始,沿着每一格的父节点移动即是路径。
代码
List<Point> CloseList;//关闭列表
List<Point> OpenList;//开启列表
//Point 类
public class Point
{
public Point ParentPoint { get; set; }
public int F { get; set; } //F=G+H
public int G { get; set; }
public int H { get; set; }
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public void CalcF()
{
this.F = this.G + this.H;
}
}
//寻路过程
public Point FindPath(Point start, Point end, bool IsIgnoreCorner)
{
OpenList.Add(start);
while (OpenList.Count != 0)
{
//找出F值最小的点
var tempStart = OpenList.MinPoint();
OpenList.RemoveAt(0);
CloseList.Add(tempStart);
//找出它相邻的点
var surroundPoints = SurrroundPoints(tempStart, IsIgnoreCorner);
foreach (Point point in surroundPoints)
{
if (OpenList.Exists(point))
//计算G值, 如果比原来的大, 就什么都不做, 否则设置它的父节点为当前点,并更新G和F
FoundPoint(tempStart, point);
else
//如果它们不在开始列表里, 就加入, 并设置父节点,并计算GHF
NotFoundPoint(tempStart, end, point);
}
if (OpenList.Get(end) != null)
return OpenList.Get(end);
}
return OpenList.Get(end);
}