0

We know Floyd-Warshal algorithm gives us the shortest cost/path to go any node from anyother node.

For example:

enter image description here

From above image we can achieve the below matrix as a result of Floyd-Warshal algo as all pair shortest path(cost)

enter image description here

If you want to go from node 4 to node 3 then there are two ways

  • 4 --> 2 --> 3 (cost is 2)
  • 4 --> 2 --> 1 --> 3 (cost is 1. So this is shortest route)

From the matrix we are seeing that the value of Row 4 and Column 3 is 1. So this is showing us the shortest cost between these two nodes.

Now my question is -

How can I get the route as well (4-->2-->1-->3) ?

ravenspoint
  • 19,093
  • 6
  • 57
  • 103
Shamim
  • 635
  • 2
  • 12
  • 28

1 Answers1

0

When you have negative edge costs, the trick is to add the absolute value of the smallest cost to every edge ( so that all edges have a zero or positive cost ) In your example, add 2 to every edge cost.

Then the cheapest path can be found in the usual way.

ravenspoint
  • 19,093
  • 6
  • 57
  • 103
  • This is incorrect, counter-example: `G = (a,b) : 5, (b,c) : 2, (c,a) : -10`, assuming you start from `a`, you can infinitely cycle to keep reducing distance. – ldog Oct 29 '21 at 00:19
  • Your approach also does not work with no negative cycles, counter-example: `G = (a,b) : 5, (b,c) : -10, (a,c) : 2`, then the cheapest paths from `a` are `(a->b) : 2` and `(a->b->c): -5`. With your method, it states cheapest paths are `(a->b) : 15`, `(a->c) : 12`, which is incorrect for the path `a->c`. – ldog Oct 29 '21 at 00:22
  • @idog You need to read my answer more carefully. – ravenspoint Oct 29 '21 at 00:33
  • Actually I didn't ask to find smallest cost rather asked how can I find the route of that smallest path ? Like, A ---> C ---> D – Shamim Oct 29 '21 at 05:55
  • I am confused. In your post you number the vertices ( 1,2,3,...) In your comment you give them letters ( A,C,D ). Can you clarify please? – ravenspoint Oct 29 '21 at 12:48