View Single Post
  #4  
Old November 6th, 2009, 03:24 PM
TriKri's Avatar
TriKri TriKri is offline
Senior Member
 
Join Date: Nov 2006
Posts: 284
Country:
Thanks: 31
Thanked 24 Times in 23 Posts
TriKri is on a distinguished road
Default

I think a program solving this problem would perform best if applying dynamic programming of some sort, but other methods would of course also solve the problem.

One solution using dynamic programming would be this:

Create a list, list a, of pairs consisting of a number (the total cost), and a vector containing Boolean values; one Boolean value for each node. The vectors represent states in the graph (which nodes have been visited and which have not), and the number is the minimum cost to get to that state. From the beginning, the list only contains one pair; 0 (the starting cost) and a vector containing only false at each element except from the element representing S.

Now, as long as you don't have any vector where the element representing D is true, do the following:

Create a new empty list, list b. For each pair in list a, consisting of a number n1, and a vector v1, representing state s1, consider each new state s2, that can be reached from s1, using only one move. Create a new vector v2, that represents s2, where all elements have the same value as in v1, except the element that represents the node differing between s2 and s1 (which should now be true), along with a number n2 = n1 + the cost to move from s1 to s2. If a pair in list b containing v2 has a number that is higher than n2, lower that number to n2. If no pair in list b contains v2, add a new pair to the list consisting of n2 and v2. When all pairs in list a have been looped through, replace it with list b, and if no pair's vector in the new list a has the element representing D set to true, start the cycle again.

When list a does contain a pair which vector's element representing D is set to true, the number in the pair will be the lowest cost to get from S to D. Note that this is only the cost of the shortest path; to get the actual shortest path, one could use backtracking from here, or one could save yet another element in each pair, representing the previous state, making the pairs triplets.
__________________
Don't worry, be happy <°)))><
Reply With Quote