algorithm - R中2个顶点之间的所有路径

标签 algorithm r graph igraph

我使用 igraph。

我希望你找到 2 个节点之间的所有可能路径。

目前,似乎不存在任何函数来查找 igraph 中 2 个节点之间的所有路径

我发现这个主题给出了 python 代码: All possible paths from one node to another in a directed tree (igraph)

我试图将它移植到 R,但我遇到了一些小问题。它给了我错误:

Error of for (newpath in newpaths) { : 
  for() loop sequence incorrect

代码如下:

find_all_paths <- function(graph, start, end, mypath=vector()) {
  mypath = append(mypath, start)

  if (start == end) {
    return(mypath)
  }

  paths = list()

  for (node in graph[[start]][[1]]) {
     if (!(node %in% mypath)){
      newpaths <- find_all_paths(graph, node, end, mypath)
      for (newpath in newpaths){
        paths <- append(paths, newpath)
      }
     }
  }
  return(paths)
}

test <- find_all_paths(graph, farth[1], farth[2])

这是从 igrah 包中获取的虚拟代码,可以从中获取示例图和节点:

actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David",
                             "Esmeralda"),
                      age=c(48,33,45,34,21),
                      gender=c("F","M","F","M","F"))
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David",
                                "David", "Esmeralda"),
                         to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
                         same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE),
                         friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3))
g <- graph.data.frame(relations, directed=FALSE, vertices=actors)

farth <- farthest.nodes(g)

test <- find_all_paths(graph, farth[1], farth[2])

谢谢!

如果有人看到问题出在哪里,那将有很大帮助...

马修

最佳答案

我还尝试将相同的解决方案从 Python 转换为 R 并提出了以下似乎适合我的工作:

# Find paths from node index n to m using adjacency list a.
adjlist_find_paths <- function(a, n, m, path = list()) {
  path <- c(path, list(n))
  if (n == m) {
    return(list(path))
  } else {
    paths = list()
    for (child in a[[n]]) {
      if (!child %in% unlist(path)) {
        child_paths <- adjlist_find_paths(a, child, m, path)
        paths <- c(paths, child_paths)
      }
    }
    return(paths)
  }
}

# Find paths in graph from vertex source to vertex dest.
paths_from_to <- function(graph, source, dest) {
  a <- as_adj_list(graph, mode = "out")
  paths <- adjlist_find_paths(a, source, dest)
  lapply(paths, function(path) {V(graph)[unlist(path)]})
}

关于algorithm - R中2个顶点之间的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16668466/

相关文章:

r - 检测 R 中的可用和空闲内核

r - 为什么 intersect(...) 比数据表连接快?

找到多个短路径的算法

algorithm - 查找图形算法的封闭部分

algorithm - 顶点着色/分配以最小化 "color crossings"的数量

r - 传递空省略号参数时的不同行为

r - 如何在 R 中绘制带有条件 p 值和置信区间的方差分析?

algorithm - NP 硬度边界

c++ - 为什么C++标准要求std::partition来满足不同类型迭代器的不同复杂度?

algorithm - 如何找到 $\sqrt(x)$ 形式的无理数的第 n 个数字