转载自:http://www.cnblogs.com/technology/archive/2011/05/26/2058842.html
把起始格添加到 "开启列表"
do
{
寻找开启列表中F值最低的格子, 我们称它为当前格.
把它切换到关闭列表.
对当前格相邻的8格中的每一个
if (它不可通过 || 已经在 "关闭列表" 中)
{
什么也不做.
}
if (它不在开启列表中)
{
把它添加进 "开启列表", 把当前格作为这一格的父节点, 计算这一格的 FGH
if (它已经在开启列表中)
{
if (用G值为参考检查新的路径是否更好, 更低的G值意味着更好的路径)
{
把这一格的父节点改成当前格, 并且重新计算这一格的 GF 值.
}
} while( 目标格已经在 "开启列表", 这时候路径被找到)
如果开启列表已经空了, 说明路径不存在.
最后从目标格开始, 沿着每一格的父节点移动直到回到起始格, 这就是路径.
List<Point> CloseList;
List<Point> OpenList;
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);
}