Search code examples
c#algorithmshortest-pathdijkstraquickgraph

QuickGraph Dijkstra example


I have an AdjacencyGraph<string, Edge<string>> which I would like to run AlgorithmExtensions.ShortestPathsDijkstra on, but the QuickGraph documentation isn't the best.

Does anyone have an example I can follow?

Everything I found on Google used an observer, which the AlgorithmExtension doesn't require.


Solution

  • I've updated the docs but in a nutshell, you need a graph, a edge weight map (as a delegate) and a root vertex. The AlgorithmExtensions method returns a 'TryFunc' that you can query to fetch shortest paths.

    using QuickGraph;
    using QuickGraph.Algorithms;
    
    IVertexAndEdgeListGraph<TVertex, TEdge> graph = ...;
    Func<TEdge, double> edgeCost = e => 1; // constant cost
    TVertex root = ...;
    
    // compute shortest paths
    TryFunc<TVertex, TEdge> tryGetPaths = graph.ShortestPathDijkstra(edgeCost, root);
    
    // query path for given vertices
    TVertex target = ...;
    IEnumerable<TEdge> path;
    if (tryGetPaths(target, out path))
        foreach(var edge in path)
            Console.WriteLine(edge);