2之间的顶点在研发所有的路径有的、顶点、路径

2023-09-11 05:28:47 作者:走着走着就散了

我用的igraph。

我想哟找到2个节点之间的所有可能路径。

I want yo find all the possible paths between 2 nodes.

目前,似乎没有存在任何功能,找到所有的IGRAPH两个节点之间的路径

For the moment, there doesn't seem to exist any function to find all the paths between 2 nodes in igraph

我发现这个主题,让code在python: All从一个节点在向树可能的路径到另一个(IGRAPH)

I found this subject that gives code in python: All possible paths from one node to another in a directed tree (igraph)

我试图将它移植于R,但我有一些小问题。它给我的错误:

I tried to port it to R but I have some little problems. It gives me the error:

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

下面是code:

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包,从中获取的样本图和节点采取虚设code:

Here is a dummy code taken from the igrah package, from which to get a sample graph and nodes:

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])

谢谢!

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

If anyone sees where the problem, that would be of great help...

马修

推荐答案

我也试图从翻译的Python至R相同的解决方案,并提出了这似乎做的工作,我的情况如下:

I also attempted to translate that same solution from Python to R and came up with the following which seems to do the job for me:

# 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)]})
}