簡體   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