Cheapest path

You can twist bell-man ford algorithm to solve this problem. Let s be the source node, t be the destination node, dist be the distance matrix . I am writing a pseudo code to solve this problem. This works only if G does not have a negative cycle. You can use dijkastra to solve in that case. Hopefully you will be able to implement using your preferred language:

routine (G, s, t):

dist[0][s] = 0

dist[0][v] = inf for v in Vertex_set and v = s

for i = 1..k do

dist\[k\]\[v\] = dist\[k − 1\]\[v\]

for any e=(u, v) in Edge\_set do 

    dist\[k\]\[v\] = min(dist\[k\]\[v\], dist\[k − 1\]\[u\] + cost\[u\]\[v\]) //cost\[u\]\[v\] is cost from u to v 

return dist[k][t]

Space complexity for this code can be reduced using vector based implementation of Hop-based recursive bellman ford.

/r/GraphTheory Thread