![](/img/trans.png)
[英]Creating a undirected graph and traversing it using BFS in QuickGraph
[英]Getting connected components from a QuickGraph graph
我是圖論的新手。
我已經使用QuickGraph庫創建了一個鄰接圖,最終,我希望從圖中獲得連接的組件。
open QuickGraph
let tup = [(1M,1M); (2M, 18M); (3M, 3M); (4M, 5M); (5M, 24M); (24M, 6M); (7M, 6M); (8M, 9M); (10M, 9M)]
type Vertex = {decimal: decimal}
let edges =
tup
|> List.map (fun x -> ({decimal = fst x}, {decimal = snd x}))
|> List.map (fun x -> Edge<Vertex> x)
//Undirected Graph
let undirGraph = edges.ToUndirectedGraph()
undirGraph.Edges
undirGraph.Vertices
let x = QuickGraph.Algorithms.ConnectedComponents.ConnectedComponentsAlgorithm(undirGraph)
undirGraph.Edges
輸出:
val it : Collections.Generic.IEnumerable<Edge<Vertex>> =
seq
[FSI_0227+Vertex->FSI_0227+Vertex {Source = {decimal = 1M;};
Target = {decimal = 1M;};};
FSI_0227+Vertex->FSI_0227+Vertex {Source = {decimal = 2M;};
Target = {decimal = 18M;};};
FSI_0227+Vertex->FSI_0227+Vertex {Source = {decimal = 3M;};
Target = {decimal = 3M;};};
FSI_0227+Vertex->FSI_0227+Vertex {Source = {decimal = 4M;};
Target = {decimal = 5M;};}; ...]
並且來自undirGraph.Vertices
:
val it : Collections.Generic.IEnumerable<Vertex> =
seq
[{decimal = 1M;}; {decimal = 2M;}; {decimal = 18M;}; {decimal = 3M;}; ...]
正如所料。
無向圖已成功創建,但現在我被卡住了。 從這里開始,我不知道如何獲取圖形的連通組件,或者坦率地說,如果我使用正確的圖形結構。
我希望x
包含圖中的組件但是從x;;
輸出x;;
在FSI看起來像這樣:
示例tuple list
的值表示BillTo
和ShipTo
客戶ID值。
QuickGraph庫中的文檔很少,特別是對於那些試圖“即時學習”的人。
這是你要找的東西嗎?
我會使用RProvider將代碼發送到R並生成它,然后在必要時將其包裝在dll中。 然后,您可以使用components
, clusters
, groups
等來提取連接。
# In R:
g1 <- graph( edges=c( "1","1", "2", "18", "3", "3", "4", "5", "5", "24", "24", "6", "7", "6", "8", "9", "10", "9"),n=9,directed=T)
plot(g1)
comp1 <- components(g1)
comp1
groups(comp1)
cl <- clusters(g1)
lapply(seq_along(cl$csize)[cl$csize > 1], function(x)
V(g1)$name[cl$membership %in% x])
如果您決定仍然堅持使用QuickGraph,您在FSI中看到的是因為您正在定義一個名為Vertex
的記錄類型,其中有一個名為decimal的十進制成員。 這有點讓人困惑,所以最初我建議你堅持使用int
並按以下方式生成圖形:
let tup = [(1,1); (2, 18); (3, 3); (4, 5); (5, 24); (24, 6); (7, 6); (8, 9); (10, 9)]
let edges =
tup |> List.map (fun x -> SEdge<int>(fst x, snd x))
let graph = edges.ToAdjacencyGraph()
let uniGraph = edges.ToUndirectedGraph()
你也可以寫一些像數據結構這樣的字典來保存引用的記錄/數量。
事實證明,你需要在算法上調用Compute
方法來實際運行它!
我拿了你的示例代碼,只是添加了對Compute
調用:
let x = QuickGraph.Algorithms.ConnectedComponents.
ConnectedComponentsAlgorithm(undirGraph)
x.Compute()
一旦你這樣做, x.Components
包含一個字典,為每個頂點分配一個組件的索引,所以如果你想要頂點組(代表組件),你可以只用Value
(它是組件索引)對結果進行分組:
x.Components
|> Seq.groupBy (fun kv -> kv.Value)
|> Seq.map (fun (comp, vertices) ->
comp, vertices |> Seq.map (fun kv -> kv.Key))
這給出了以下內容:
[ (0, [{decimal = 1M;}]);
(1, [{decimal = 2M;}; {decimal = 18M;}]);
(2, [{decimal = 3M;}]);
(3, [{decimal = 4M;}; {decimal = 5M;}; {decimal = 24M;};
{decimal = 6M;}; {decimal = 7M;}]);
(4, [{decimal = 8M;}; {decimal = 9M;}; {decimal = 10M;}]) ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.