gpt4 book ai didi

c#-4.0 - QuickGraph 库中的加权有向图

转载 作者:行者123 更新时间:2023-12-02 20:07:38 27 4
gpt4 key购买 nike

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

enter image description here

我想以这样的方式用 C# 进行编码,以便我可以询问结构并找到如下信息:

  • AB的总距离。
  • AE的最短距离(保持在请注意,您不能逆着箭头的方向前进)。

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

我遇到了this Library在各种主题上都推荐过几次,但我发现它对我上面绘制的图表进行建模确实很困难。

最佳答案

一个可能的解决方案是将您的图表建模为 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现在是:

your 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

关于c#-4.0 - QuickGraph 库中的加权有向图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18477081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com