Everyone else, comparing this to the Traveling Salesman problem, probably did not carefully read your question. In TSP, the task is to find the shortest loop that visits all the vertices (Hamiltonian loop) - this corresponds to the fact that each node is marked as mandatory.
In your case, given that you only have about a dozen labeled "mustpass", and given that 12! (479001600), you can just try all permutations of only the mustpass nodes and see the shortest path from start to end that visits the mustpass nodes in that order - it’s just being a concatenation of the shortest paths between every two consecutive nodes in on this list.
In other words, first find the shortest distance between each pair of vertices (you can use the Dijkstra algorithm or others, but with such small numbers (100 nodes), even the simplest
Floyd-Warsall algorithm in the code
will start in time). Then, as soon as you get this in the table, try all the permutations of your "required" nodes, and the rest.
Something like that:
//Precomputation: Find all pairs shortest paths, eg using Floyd-Warshall n = number of nodes for i=1 to n: for j=1 to n: d[i][j]=INF for k=1 to n: for i=1 to n: for j=1 to n: d[i][j] = min(d[i][j], d[i][k] + d[k][j]) //That *really* gives the shortest distance between every pair of nodes! :-) //Now try all permutations shortest = INF for each permutation a[1],a[2],...a[k] of the 'mustpass' nodes: shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end']) print shortest
(Of course, this is not real code, and if you need the actual path, you will need to keep track of which permutation gives the shortest distance, and also that all paired shortest paths, but you get the idea.)
It will work in a few seconds in any reasonable language :)
[If you have n nodes and k 'mustpass' nodes, its runtime is O (n 3 ) for the Floyd-Warshall part, and O (k! N) for the entire part of the permutations and 100 ^ 3 + (12!) ( 100) is practically peanuts unless you have really restrictive restrictions.]
ShreevatsaR Oct 23 '08 at 1:50 2008-10-23 01:50
source share