title: Find the shortest path using dijkstras Algorithm in R
body: <p>I am trying to find shortest path between cities using dijkstras Algorithm. I referred this post</p>
  <p><a href="https://www.r-bloggers.com/2020/10/finding-the-shortest-path-with-dijkstras-algorithm/" rel="nofollow noreferrer">https://www.r-bloggers.com/2020/10/finding-the-shortest-path-with-dijkstras-algorithm/</a></p>
  <p>Based on this I tried to implement for my own set of input.</p>
  <p>When I tried to find the shortest path between given cities I am getting NULL.</p>
  <p><strong>My Input</strong></p>
  <pre><code>input &lt;- suppressWarnings(readLines(stdin(), n=6))
  
  5 5
  london berlin 30
  london istanbul 10
  berlin singapore 40
  istanbul dhaka 20
  dhaka singapore 30
  </code></pre>
  <p>Line 1 first 5 represent total number of cities. Second 5 represent possible number of roads / number of rows among them.</p>
  <p><strong>My Code</strong></p>
  <pre><code>l1 &lt;- unlist(strsplit(input[1],&quot; &quot;))
   cities &lt;- as.numeric(l1[1])
   roads &lt;- as.numeric(l1[2])
  
  val &lt;- 1:roads
  for (i in 1:roads )  
   {
     val[i] &lt;- strsplit(input[i+1],&quot; &quot;)
  
  } 
  
  df &lt;- data.frame(t(sapply(val,c)))
  
  colnames(df) &lt;- c('from','to','cost')
  
  # From Here referring the algorithm
  
  path_length &lt;- function(path) {
    # if path is NULL return infinite length
    if (is.null(path)) return(&quot;NOT POSSIBLE&quot;)
    
    # get all consecutive nodes
    pairs &lt;- cbind(from = path[-length(path)], to = path[-1])
    # join with G and sum over cost
    sum(merge(pairs, df)[ , &quot;cost&quot;])
  }
  
  find_shortest_path &lt;- 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 &lt;- c(path, start)
    
    # base case of recursion: if end is reached return path
    if (start == end) return(path)
    
    # initialize shortest path as NULL
    shortest &lt;- 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 &lt;- find_shortest_path(graph, node, end, path)
        # if newpath is shorter than shortest so far assign newpath to shortest
        if (path_length(newpath) &lt; path_length(shortest))
          shortest &lt;- newpath
      }
    }
    # return shortest path
    shortest
  }
  
  find_shortest_path(df, &quot;london&quot;, &quot;singapore&quot;)
  
  </code></pre>
  <p>I am new to R . Apologies in case of any bad programming.</p>