【发布时间】:2012-06-11 15:26:59
【问题描述】:
我无法有效地实现 Eric Lippert 推荐的这个通用方法。他的博客概述了一种非常简单有效的创建 A Star 算法的方法 (found here)。这是快速运行。
实际寻路的代码:
class Path<Node> : IEnumerable<Node>
{
public Node LastStep { get; private set; }
public Path<Node> PreviousSteps { get; private set; }
public double TotalCost { get; private set; }
private Path(Node lastStep, Path<Node> previousSteps, double totalCost)
{
LastStep = lastStep;
PreviousSteps = previousSteps;
TotalCost = totalCost;
}
public Path(Node start) : this(start, null, 0) { }
public Path<Node> AddStep(Node step, double stepCost)
{
return new Path<Node>(step, this, TotalCost + stepCost);
}
public IEnumerator<Node> GetEnumerator()
{
for (Path<Node> p = this; p != null; p = p.PreviousSteps)
yield return p.LastStep;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
class AStar
{
static public Path<Node> FindPath<Node>(
Node start,
Node destination,
Func<Node, Node, double> distance,
Func<Node, double> estimate)
where Node : IHasNeighbours<Node>
{
var closed = new HashSet<Node>();
var queue = new PriorityQueue<double, Path<Node>>();
queue.Enqueue(0, new Path<Node>(start));
while (!queue.IsEmpty)
{
var path = queue.Dequeue();
if (closed.Contains(path.LastStep))
continue;
if (path.LastStep.Equals(destination))
return path;
closed.Add(path.LastStep);
foreach (Node n in path.LastStep.Neighbours)
{
double d = distance(path.LastStep, n);
if (n.Equals(destination))
d = 0;
var newPath = path.AddStep(n, d);
queue.Enqueue(newPath.TotalCost + estimate(n), newPath);
}
}
return null;
}
/// <summary>
/// Finds the distance between two points on a 2D surface.
/// </summary>
/// <param name="x1">The IntPoint on the x-axis of the first IntPoint</param>
/// <param name="x2">The IntPoint on the x-axis of the second IntPoint</param>
/// <param name="y1">The IntPoint on the y-axis of the first IntPoint</param>
/// <param name="y2">The IntPoint on the y-axis of the second IntPoint</param>
/// <returns></returns>
public static long Distance2D(long x1, long y1, long x2, long y2)
{
// ______________________
//d = √ (x2-x1)^2 + (y2-y1)^2
//
//Our end result
long result = 0;
//Take x2-x1, then square it
double part1 = Math.Pow((x2 - x1), 2);
//Take y2-y1, then sqaure it
double part2 = Math.Pow((y2 - y1), 2);
//Add both of the parts together
double underRadical = part1 + part2;
//Get the square root of the parts
result = (long)Math.Sqrt(underRadical);
//Return our result
return result;
}
/// <summary>
/// Finds the distance between two points on a 2D surface.
/// </summary>
/// <param name="x1">The IntPoint on the x-axis of the first IntPoint</param>
/// <param name="x2">The IntPoint on the x-axis of the second IntPoint</param>
/// <param name="y1">The IntPoint on the y-axis of the first IntPoint</param>
/// <param name="y2">The IntPoint on the y-axis of the second IntPoint</param>
/// <returns></returns>
public static int Distance2D(int x1, int y1, int x2, int y2)
{
// ______________________
//d = √ (x2-x1)^2 + (y2-y1)^2
//
//Our end result
int result = 0;
//Take x2-x1, then square it
double part1 = Math.Pow((x2 - x1), 2);
//Take y2-y1, then sqaure it
double part2 = Math.Pow((y2 - y1), 2);
//Add both of the parts together
double underRadical = part1 + part2;
//Get the square root of the parts
result = (int)Math.Sqrt(underRadical);
//Return our result
return result;
}
public static long Distance2D(Point one, Point two)
{
return AStar.Distance2D(one.X, one.Y, two.X, two.Y);
}
}
PriorityQueue 代码:
class PriorityQueue<P, V>
{
private SortedDictionary<P, Queue<V>> list = new SortedDictionary<P, Queue<V>>();
public void Enqueue(P priority, V value)
{
Queue<V> q;
if (!list.TryGetValue(priority, out q))
{
q = new Queue<V>();
list.Add(priority, q);
}
q.Enqueue(value);
}
public V Dequeue()
{
// will throw if there isn’t any first element!
var pair = list.First();
var v = pair.Value.Dequeue();
if (pair.Value.Count == 0) // nothing left of the top priority.
list.Remove(pair.Key);
return v;
}
public bool IsEmpty
{
get { return !list.Any(); }
}
}
以及获取附近节点的接口:
interface IHasNeighbours<N>
{
IEnumerable<N> Neighbours { get; }
}
这是我无法有效实施的部分。我可以创建一个能够被路径查找使用的类,但是查找附近的节点变得很痛苦。本质上,我最终要做的是创建一个类,在这种情况下,它被视为单个图块。但是,为了获取所有附近的节点,我必须将一个值传递给该图块,其中包含所有其他图块的列表。这非常麻烦,让我相信一定有更简单的方法。
这是我使用 System.Drawing.Point 包装器的实现:
class TDGrid : IHasNeighbours<TDGrid>, IEquatable<TDGrid>
{
public Point GridPoint;
public List<Point> _InvalidPoints = new List<Point>();
public Size _GridSize = new Size();
public int _GridTileSize = 50;
public TDGrid(Point p, List<Point> invalidPoints, Size gridSize)
{
GridPoint = p;
_InvalidPoints = invalidPoints;
_GridSize = gridSize;
}
public TDGrid Up(int gridSize)
{
return new TDGrid(new Point(GridPoint.X, GridPoint.Y - gridSize));
}
public TDGrid Down(int gridSize)
{
return new TDGrid(new Point(GridPoint.X, GridPoint.Y + gridSize));
}
public TDGrid Left(int gridSize)
{
return new TDGrid(new Point(GridPoint.X - gridSize, GridPoint.Y));
}
public TDGrid Right(int gridSize)
{
return new TDGrid(new Point(GridPoint.X + gridSize, GridPoint.Y));
}
public IEnumerable<TDGrid> IHasNeighbours<TDGrid>.Neighbours
{
get { return GetNeighbours(this); }
}
private List<TDGrid> GetNeighbours(TDGrid gridPoint)
{
List<TDGrid> retList = new List<TDGrid>();
if (IsGridSpotAvailable(gridPoint.Up(_GridTileSize)))
retList.Add(gridPoint.Up(_GridTileSize)); ;
if (IsGridSpotAvailable(gridPoint.Down(_GridTileSize)))
retList.Add(gridPoint.Down(_GridTileSize));
if (IsGridSpotAvailable(gridPoint.Left(_GridTileSize)))
retList.Add(gridPoint.Left(_GridTileSize));
if (IsGridSpotAvailable(gridPoint.Right(_GridTileSize)))
retList.Add(gridPoint.Right(_GridTileSize));
return retList;
}
public bool IsGridSpotAvailable(TDGrid gridPoint)
{
if (_InvalidPoints.Contains(gridPoint.GridPoint))
return false;
if (gridPoint.GridPoint.X < 0 || gridPoint.GridPoint.X > _GridSize.Width)
return false;
if (gridPoint.GridPoint.Y < 0 || gridPoint.GridPoint.Y > _GridSize.Height)
return false;
return true;
}
public override int GetHashCode()
{
return GridPoint.GetHashCode();
}
public override bool Equals(object obj)
{
return this.GridPoint == (obj as TDGrid).GridPoint;
}
public bool Equals(TDGrid other)
{
return this.GridPoint == other.GridPoint;
}
}
列表 _InvalidPoints 是我失败的地方。我可以将它传递给每个创建的 TDGrid,但考虑到所有其余代码的简单程度,这似乎是一种巨大的资源浪费。我知道这是我缺乏知识,但我一直无法搜索。
肯定还有别的实现方式:
interface IHasNeighbours<N>
{
IEnumerable<N> Neighbours { get; }
}
有人对此有什么想法吗?
编辑—— 这是寻路代码:
public void FindPath(TDGrid start, TDGrid end)
{
AStar.FindPath<TDGrid>(start, end, (p1, p2) => { return AStar.Distance2D(p1.GridPoint, p2.GridPoint); }, (p1) => { return AStar.Distance2D(p1.GridPoint, end.GridPoint); });
}
【问题讨论】:
-
嗯...我是否正确理解
invalidPoints列表是一组不可遍历的图块位置(即,A* 搜索需要绕行)?这里有一个想法:为什么不只保留一个 NxN 节点数组来表示每个可能的图块,并让每个节点都有一个附加的“遍历成本”,指示穿过该图块需要多少时间。然后,您的无效图块只是成本无限大的节点(或者,为了更简单,类似cost = int.MaxValue),A* 将绕过它们就好了。 -
为什么不生成一组完整的图块位置,其中每个图块都有指向其邻居的指针?然后你可以生成这个集合一次,将它存储在某个地方,这样你就可以从中获取初始点,然后继续使用它。将任何无效的邻居保留为空(如果需要条件不可用的地形,这将不起作用,但您可以按照相同的思路即兴创作)。
-
Jon - 这正是 IHasNeighbours 界面设计的目的。上面的例子,只要通过List
,就会给我那个选项,但是我觉得效率很低。我正在考虑开设一个实现 IHasNeighbours 的大师班,但不知道如何实现该目标。 -
Daniel - 是的 InvalidPoints 是所有不能成为“邻居”的位置的列表。我没有添加实际的寻路代码,但我会把它放进去。我的问题不在于实际的 A Star 算法,而在于 IHasNeighbours 的实现。
-
您的实现并不完全是我的意思,因为邻居(上、下、左、右)的吸气剂返回新的 TDGrid 点,而不是您可以早先初始化的点。如果你有东西生成结构并且该类负责设置邻居的(或在 TDGrid 上调用一些初始化方法),你可以在不传递任何东西的情况下做无效点。因此,将邻居存储为变量并为上、下、左、右添加设置器。我现在的问题似乎是你不断地初始化新的 TDGrid 对象。