How to set target vertex in QuickGraph Dijkstra or A*

二次信任 提交于 2019-12-05 03:33:28

问题


I am using QuickGraph version 3.6 and I found function SetRootVertex, but no SetTagretVertex. I need this because I am searching short paths in huge graph and this would speed up program a lot.

Clases in question are DijkstraShortestPathAlgorithm and AStarShortestPathAlgorithm.


回答1:


I don't think there is a way to this without using events.

You could wrap the necessary code in one extension method, making things clear, e.g.:

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();
    }
}

Usage:

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);


来源:https://stackoverflow.com/questions/8606494/how-to-set-target-vertex-in-quickgraph-dijkstra-or-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!