4

I'm making an implementation of the Floyd-Warshall algorithm, and I have one question: If I have a loop in my graph (I mean, the cost of going from A to A is 1), what should the algorithm output, 0 (because the cost of going from any node to the same node is 0), or 1 (because there is an edge from A to A of cost 1?

I don't include any code because that's simply that question.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ernestina Juan
  • 957
  • 1
  • 9
  • 24
  • 0 because that's simply the answer :) – biziclop Oct 20 '15 at 09:17
  • 1
    This also depends on whether the weight of the loop is negative. If loops with negative weights are permitted, the length of the shortest path may be arbitrarily small by repeating said loop. – Codor Oct 20 '15 at 09:19
  • No, loops with negative weights are not permitted, so the answer then should be 0... Thank you! – Ernestina Juan Oct 20 '15 at 09:22
  • Basically you should initialise your distance matrix to infinity for any two different vertices and to zero on the diagonal, and you won't have to worry about it afterwards. – biziclop Oct 20 '15 at 09:27

1 Answers1

0

In the Wikipedia article on the Floyd-Warhsall algorithm there is a paragraph discussing explicitly how to deal with cycles of negative length as follows.

A negative cycle is a cycle whose edges sum to a negative value. There is no shortest path between any pair of vertices i, j which form part of a negative cycle, because path-lengths from i to j can be arbitrarily small (negative). For numerically meaningful output, the Floyd–Warshall algorithm assumes that there are no negative cycles. Nevertheless, if there are negative cycles, the Floyd–Warshall algorithm can be used to detect them.

Including the details, finally the inner workings of the algorithm can be utilized as follows.

Hence, to detect negative cycles using the Floyd–Warshall algorithm, one can inspect the diagonal of the path matrix, and the presence of a negative number indicates that the graph contains at least one negative cycle.

Codor
  • 17,447
  • 9
  • 29
  • 56