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

3

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

有关的类是DijkstraShortestPathAlgorithm和AStarShortestPathAlgorithm。

1个回答

5

我认为没有办法在不使用事件的情况下完成这个任务。

你可以将必要的代码封装在一个扩展方法中,使其更加清晰易懂,例如:

public static class Extensions
{
    class AStarWrapper<TVertex, TEdge>
    where TEdge : IEdge<TVertex>
    {
        private TVertex target;
        private AStarShortestPathAlgorithm<TVertex, TEdge> innerAlgorithm;
        public AStarWrapper(AStarShortestPathAlgorithm<TVertex, TEdge> innerAlgo, TVertex root, TVertex target)
        {
            innerAlgorithm = innerAlgo;
            this.innerAlgorithm.SetRootVertex(root);
            this.target = target;
            this.innerAlgorithm.FinishVertex += new VertexAction<TVertex>(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<TVertex, TEdge>(this AStarShortestPathAlgorithm<TVertex, TEdge> algo, TVertex start, TVertex end)
        where TEdge : IEdge<TVertex>
    {
        var wrap = new AStarWrapper<TVertex, TEdge>(algo, start, end);
        return wrap.Compute();
    }
}

用法:

var g = new BidirectionalGraph<int, IEdge<int>>();

g.AddVerticesAndEdge(new Edge<int>(1, 2));
g.AddVerticesAndEdge(new Edge<int>(2, 3));
g.AddVerticesAndEdge(new Edge<int>(3, 4));
g.AddVerticesAndEdge(new Edge<int>(2, 4));

var astar =new AStarShortestPathAlgorithm<int,IEdge<int>>(g, x => 1.0, x => 0.0);
var dist = astar.ComputeDistanceBetween(2, 4);

不仅是正确的,而且非常详细和优雅的解决方案!非常感谢! - watbywbarif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接