Error

If a graph has cycles of negative weight, then formally the Floyd-Warshall algorithm is not applicable to such a graph.

In fact, for those pairs of vertices i and j, between which it is impossible to enter a cycle of negative weight, the algorithm will work correctly.

For the same pairs of vertices for which there is no answer (due to the presence of a negative cycle on the path between them), Floyd's algorithm will find some number (possibly strongly negative, but not necessarily) as an answer. However, Floyd's algorithm can be improved to handle such pairs of vertices neatly and output e.g. \(- \infty\).

To do this, for example, the following criterion "non-existence of the path" can be done. So, let the usual Floyd algorithm work on this graph. Then there is no shortest path between vertices i and j if and only if there is a vertex t reachable from i and from which j is reachable, for which  \(d [t][t]<0\).

In addition, when using Floyd's algorithm for graphs with negative cycles, it should be remembered that the distances that arise in the process of work can go negatively, exponentially with each phase. Therefore, you should take care against integer overflow by limiting all distances from below to some value (for example,  \(- \infty\)).

Verbally, the solution can be described as follows:
After the Floyd-Warshall algorithm has worked for the input graph, let's iterate over all pairs of vertices \((i,j)\), and for each such pair we check, infinitely the shortest path from i to j is small or not. To do this, let's iterate over the third vertex t, and if it turned out to be \(d[t][t] < 0\) (i.e. it lies in the cycle of negative weight), and it is reachable from i and j — then the path \((i,j)\) can be of infinitesimal length.

Since Floyd's algorithm sequentially relaxes the distances between all pairs of vertices (i, j), including those with i=j, and the initial distance between a pair of vertices (i, i) is equal to zero, then relaxation can occur only if vertex k such that d[i][k]+d[k][i]<0, which is equivalent to having a negative cycle through vertex i

you can read more about finding a negative cycle here: http://e-maxx.ru/algo/export_ford_bellman

The path through the cycle of negative weight becomes impossible.