2013-08-27 15 views
6

これは私の問題の例です。 にBからQuickGraphライブラリの重み付き有向グラフ

  • 総距離:私は構造を問い合わせ、そのような情報を見つけることができるような方法で、C#でこれをコーディングしたい

    enter image description here

  • 最短距離から(矢印の方向に反してはいけません)。

は、だから、私は私のグラフをモデル化するために隣接リストを使用するだろうと思ったが、その後、私は、これは一般的なものであると思って、プロセス(ホイールを再発明する必要はありませんを早める手助けするライブラリを探し始めました。など)

私はthis Libraryに出くわしました。これは、さまざまなトピックで数時間お勧めしましたが、上のグラフを実際にハードモデリングしています。

答えて

7

可能な解決策は、グラフをAdjacencyGraph<string, Edge<string>>としてモデル化し、コストがあなたの距離であるDictionary<Edge<string>, double>コスト辞書を作成することです。あなたの_graph

// ... 
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

は、その後、あなたは使用して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から構成されています。それは印刷:[GitHubの上に実施例を作業

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

(https://github.com/serra/QuickgraphExamples/blob/master/src/examples/CalculateDistance.cs) – Marijn

関連する問題