Search code examples
c#-4.0graphquickgraph

Weighted Directed Graph in QuickGraph Library


Here is an example of my problem.

enter image description here

I would like to code this in C# in such a way so that I may interrogate the structure and find information such as:

  • Total distance from A to B.
  • Shortest distance from A to E (keeping in mind you can't go against the arrow's direction).

So I thought I would use an Adjacency List to model my graph, but then I thought this is a common thing, and started looking for libraries to help quicken the process (no need to re-invent the wheel .. etc.)

I came across this Library that was recommended a couple of time on various topics, but I am finding it real hard modelling my drawn graph above.


Solution

  • A possible solution is to model your graph as an AdjacencyGraph<string, Edge<string>> and construct a Dictionary<Edge<string>, double> cost dictionary, where costs are your distances.

    // ...
    private AdjacencyGraph<string, Edge<string>> _graph;
    private Dictionary<Edge<string>, double> _costs;
    
    public void SetUpEdgesAndCosts()
    {
        _graph = new AdjacencyGraph<string, Edge<string>>();
        _costs = new Dictionary<Edge<string>, double>();
    
        AddEdgeWithCosts("A", "D", 4.0);
        // snip
        AddEdgeWithCosts("C", "B", 1.0);
    }
    
    private void AddEdgeWithCosts(string source, string target, double cost)
    {
        var edge = new Edge<string>(source, target);
        _graph.AddVerticesAndEdge(edge);
        _costs.Add(edge, cost);
    }
    

    Your _graph is now:

    your graph

    Then you can find the shortest path from A to E using:

    private void PrintShortestPath(string @from, string to)
    {
        var edgeCost = AlgorithmExtensions.GetIndexer(_costs);
        var tryGetPath = _graph.ShortestPathsDijkstra(edgeCost, @from);
    
        IEnumerable<Edge<string>> path;
        if (tryGetPath(to, out path))
        {
            PrintPath(@from, to, path);
        }
        else
        {
            Console.WriteLine("No path found from {0} to {1}.");
        }
    }
    

    This is adapted from the QuickGraph wiki. It prints:

    Path found from A to E: A > D > B > E