我的代码段如下:
df = as.data.frame(rbind(
c("a","b",2),
c("b","d",2),
c("d","g",2),
c("g","j",8),
c("j","i",2),
c("i","f",6),
c("f","c",2),
c("c","a",4),
c("c","e",4),
c("e","h",2),
c("h","j",4),
c("e","g",1),
c("e","i",3),
c("e","b",7)
))
names(df) = c("start_node","end_node","dist")
# Convert this to "igraph" class
gdf <- graph.data.frame(df, directed=FALSE)
# Compute the min distances from 'a' to all other vertices
dst_a <- shortest.paths(gdf,v='a',weights=E(gdf)$dist)
# Compute the min distances from 'a' to 'j'
dst_a[1, which(V(gdf)$name == 'j')]
当它返回结果12时,我需要得到最短路径,在这种情况下应该是a - b - d - g - e - i - j。我曾尝试使用get.shortest.paths(),但徒劳无功。
答案 0 :(得分:2)
您使用get.shortest.paths
尝试了什么?因为这有效:
> V(gdf)[get.shortest.paths(gdf,"a","j",weights=E(gdf)$dist)[[1]]]
Vertex sequence:
[1] "a" "b" "d" "g" "e" "i" "j"
get.shortest.paths
返回长度为1的列表,因为我只是要求它计算从“a”到“j”的最短路径,所以我采用它的第一个元素。
答案 1 :(得分:2)
尝试使用get.all.shortest.paths()
。考虑到可能存在多个短路径(例如,在“a”和“e”之间尝试相同)
sp=get.all.shortest.paths(gdf, "a", "j",weights=E(gdf)$dist)
sp
$res
$res[[1]]
[1] 1 2 3 4 9 6 5
$nrgeo
[1] 1 1 1 1 1 1 1 1 1 1
V(gdf)[sp$res[[1]]]$name
[1] "a" "b" "d" "g" "e" "i" "j"