繁体   English   中英

笔迹最短距离

[英]R igraph shortest distance

我的代码段如下:

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(),但徒劳。

您尝试使用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”的最短路径,因此我采用了它的第一个元素。

尝试使用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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM