这是我的问题的一个例子。
我想以这种方式在C#中对此进行编码,以便我可以查询结构并查找以下信息:
所以我想我会用一个邻接列表来模拟我的图形,但后来我认为这是常见的事情,并开始寻找库来帮助加快这个过程(不需要重新发明轮子......等等。 )
我偶然发现了this Library在各种主题上被推荐了几次,但我发现上面绘制的图形真的很难建模。
答案 0 :(得分:8)
一种可能的解决方案是将图表建模为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