![](/img/trans.png)
[英]How does ` igraph` calculate the shortest path in a weighted directed network, using Dijkstra's Algorithm?
[英]Is R IGraph computing undirected shortest path in directed network?
關於IGraph最短路徑計算,我缺少一些東西。
假設我生成一個網絡(在stackoverflow中的某個地方找到)並執行簡單的計算:
library(igraph);
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"), to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"));
g = simplify(graph_from_data_frame(d=relations, directed=T), remove.multiple = F, remove.loops = T);
#plotting the network in order to appreciate the directions of the edges
plot(g,edge.arrow.size=0.5);
#V(g)[5] is "Alice" which apparently should not be able to reach any node
print(all_shortest_paths(g,from=V(g)[5],to=V(g),mode="all")$res);
如您所見,找到的最短路徑是:
> print(all_shortest_paths(g,from=V(g)[5],to=V(g),mode="all")$res);
[[1]]
+ 2/5 vertices, named, from 823c15d:
[1] Alice Bob
[[2]]
+ 2/5 vertices, named, from 823c15d:
[1] Alice Cecil
[[3]]
+ 2/5 vertices, named, from 823c15d:
[1] Alice David
[[4]]
+ 2/5 vertices, named, from 823c15d:
[1] Alice Esmeralda
[[5]]
+ 1/5 vertex, named, from 823c15d:
[1] Alice
我期望的是,不應該返回最短的路徑,因為在有向圖中,愛麗絲沒有從其自身伸出的邊緣。 這是由於以下事實:當我計算最短路徑時,我正在使用以下選項:
mode="all"
而且這以某種方式甚至適用於有向圖?
當然,如果我更改圖形構造並設置:
directed=F
即
library(igraph);
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"), to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"));
g = simplify(graph_from_data_frame(d=relations, directed=F), remove.multiple = F, remove.loops = T);
#plottin the network in order to appreciate the directions of the edges
plot(g,edge.arrow.size=0.5);
#V(g)[5] is "Alice" which apparently should not be able to reach any node
print(all_shortest_paths(g,from=V(g)[5],to=V(g),mode="all")$res);
返回相同的結果。
到底是怎么回事? 我是否太累了,無法直截了當?
這就是mode="all"
含義-使用所有邊緣而不管方向。
我將使用一個更簡單的圖形來輕松查看發生了什么。
rel2 <- data.frame(from=c("Bob", "Bob", "David"),
to=c("Alice", "Carol", "Carol"))
g = simplify(graph_from_data_frame(d=rel2, directed=T))
LO = layout_as_bipartite(g, types=c(F,F,T,T))
plot(g, layout=LO)
現在,用最短路徑聲明
print(all_shortest_paths(g,from=V(g)[3],to=V(g),mode="all")$res)
[[1]]
+ 2/4 vertices, named:
[1] Alice Bob
[[2]]
+ 4/4 vertices, named:
[1] Alice Bob Carol David
[[3]]
+ 1/4 vertex, named:
[1] Alice
[[4]]
+ 3/4 vertices, named:
[1] Alice Bob Carol
即使邊沿相反的方向,我們也可以獲得將愛麗絲連接到另一個節點的所有路徑。
我認為您想要的是:
print(all_shortest_paths(g,from=V(g)[3],to=V(g),mode="out")$res)
[[1]]
+ 1/4 vertex, named:
這僅給出了從Alice到其自身的零長度路徑。
為了完整性,
print(all_shortest_paths(g,from=V(g)[3],to=V(g),mode="in")$res)
[[1]]
+ 2/4 vertices, named:
[1] Alice Bob
[[2]]
+ 1/4 vertex, named:
[1] Alice
這僅使用進入的邊緣來遵循路徑,因此我們使用進入Alice的邊緣將路徑從“ Alice”到“ Bob”獲得,但是由於沒有進入Bob的邊緣,因此我們一無所獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.