This code searches for the shortest paths in a graph using Floyd’s algorithm. It works great for positive numbers. But when negative ones appear, it begins to make cycles and loops. How to fix it?
for k in range(n):
for i in range(n):
for j in range(n):
if i == j:
dist[i][j] = 0
else:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
As a result, I would like to get an algorithm that will not artificially create negative cycles.
New contributor
Алла Ноженко is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.