如何在QuickGraph Dijkstra或A *中设置目标顶点

我正在使用QuickGraph版本3.6,我发现函数SetRootVertex,但没有SetTagretVertex。 我需要这个,因为我在巨大的图表中搜索短路径,这将加快程序的速度。

有问题的Clases是DijkstraShortestPathAlgorithm和AStarShortestPathAlgorithm。

如果不使用事件,我认为没有办法解决这个问题。

您可以将必要的代码包装在一个扩展方法中,使事情变得清晰,例如:

public static class Extensions { class AStarWrapper where TEdge : IEdge { private TVertex target; private AStarShortestPathAlgorithm innerAlgorithm; public AStarWrapper(AStarShortestPathAlgorithm innerAlgo, TVertex root, TVertex target) { innerAlgorithm = innerAlgo; this.innerAlgorithm.SetRootVertex(root); this.target = target; this.innerAlgorithm.FinishVertex += new VertexAction(innerAlgorithm_FinishVertex); } void innerAlgorithm_FinishVertex(TVertex vertex) { if (object.Equals(vertex, target)) this.innerAlgorithm.Abort(); } public double Compute() { this.innerAlgorithm.Compute(); return this.innerAlgorithm.Distances[target]; } } public static double ComputeDistanceBetween(this AStarShortestPathAlgorithm algo, TVertex start, TVertex end) where TEdge : IEdge { var wrap = new AStarWrapper(algo, start, end); return wrap.Compute(); } } 

用法:

 var g = new BidirectionalGraph>(); g.AddVerticesAndEdge(new Edge(1, 2)); g.AddVerticesAndEdge(new Edge(2, 3)); g.AddVerticesAndEdge(new Edge(3, 4)); g.AddVerticesAndEdge(new Edge(2, 4)); var astar =new AStarShortestPathAlgorithm>(g, x => 1.0, x => 0.0); var dist = astar.ComputeDistanceBetween(2, 4);