【问题标题】:Weighted Directed Graph in QuickGraph LibraryQuickGraph 库中的加权有向图
【发布时间】:2013-08-30 21:18:41
【问题描述】:

这是我的问题的一个例子。

我想用 C# 编写代码,这样我就可以查询结构并找到如下信息:

  • AB 的总距离。
  • AE 的最短距离(保持在 注意你不能违背箭头的方向)。

所以我想我会使用邻接列表来为我的图建模,但后来我认为这是一个常见的事情,并开始寻找库来帮助加快这个过程(无需重新发明轮子......等。 )

我遇到了this Library,它曾多次被推荐用于各种主题,但我发现对上面绘制的图表进行建模非常困难。

【问题讨论】:

    标签: c#-4.0 graph quickgraph


    【解决方案1】:

    一种可能的解决方案是将您的图表建模为AdjacencyGraph<string, Edge<string>> 并构造一个Dictionary<Edge<string>, double> 成本字典,其中成本是您的距离。

    // ...
    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);
    }
    

    您的_graph 现在是:

    然后您可以使用以下方法找到从 A 到 E 的最短路径:

    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}.");
        }
    }
    

    这是改编自QuickGraph wiki。它打印:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-05
    • 2015-04-07
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    相关资源
    最近更新 更多