code_junkie

Find the shortest path in a graph which visits certain nodes

Nov 11th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.51 KB | None | 0 0
  1. //Precomputation: Find all pairs shortest paths, e.g. using Floyd-Warshall
  2. n = number of nodes
  3. for i=1 to n: for j=1 to n: d[i][j]=INF
  4. for k=1 to n:
  5. for i=1 to n:
  6. for j=1 to n:
  7. d[i][j] = min(d[i][j], d[i][k] + d[k][j])
  8. //That *really* gives the shortest distance between every pair of nodes! :-)
  9.  
  10. //Now try all permutations
  11. shortest = INF
  12. for each permutation a[1],a[2],...a[k] of the 'mustpass' nodes:
  13. shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end'])
  14. print shortest
Add Comment
Please, Sign In to add comment