在 R 中使用 dijkstras 算法找到最短路径

时间:2021-07-02 05:57:41

标签: r

我正在尝试使用 dijkstras 算法找到城市之间的最短路径。我参考了这个帖子

https://www.r-bloggers.com/2020/10/finding-the-shortest-path-with-dijkstras-algorithm/

基于此,我尝试为我自己的一组输入实现。

当我试图找到给定城市之间的最短路径时,我得到了 NULL。

我的输入

input <- suppressWarnings(readLines(stdin(), n=6))

5 5
london berlin 30
london istanbul 10
berlin singapore 40
istanbul dhaka 20
dhaka singapore 30

第 1 行前 5 个代表城市总数。后 5 表示可能的道路数量/其中的行数。

我的代码

l1 <- unlist(strsplit(input[1]," "))
 cities <- as.numeric(l1[1])
 roads <- as.numeric(l1[2])

val <- 1:roads
for (i in 1:roads )  
 {
   val[i] <- strsplit(input[i+1]," ")

} 

df <- data.frame(t(sapply(val,c)))

colnames(df) <- c('from','to','cost')

# From Here referring the algorithm

path_length <- function(path) {
  # if path is NULL return infinite length
  if (is.null(path)) return("NOT POSSIBLE")
  
  # get all consecutive nodes
  pairs <- cbind(from = path[-length(path)], to = path[-1])
  # join with G and sum over cost
  sum(merge(pairs, df)[ , "cost"])
}

find_shortest_path <- function(graph, start, end, path = c()) {
  # if there are no nodes linked from current node (= dead end) return NULL
  if (is.null(graph[[start]])) return(NULL)
  # add next node to path so far
  path <- c(path, start)
  
  # base case of recursion: if end is reached return path
  if (start == end) return(path)
  
  # initialize shortest path as NULL
  shortest <- NULL
  # loop through all nodes linked from the current node (given in start)
  for (node in graph[[start]]) {
    # proceed only if linked node is not already in path
    if (!(node %in% path)) {
      # recursively call function for finding shortest path with node as start and assign it to newpath
      newpath <- find_shortest_path(graph, node, end, path)
      # if newpath is shorter than shortest so far assign newpath to shortest
      if (path_length(newpath) < path_length(shortest))
        shortest <- newpath
    }
  }
  # return shortest path
  shortest
}

find_shortest_path(df, "london", "singapore")

我是 R 的新手。如有任何错误的编程,我们深表歉意。

0 个答案:

没有答案
相关问题