When you need distances between every pair of vertices, Floyd-Warshall handles negative edges in one compact triple loop.
Implement floyd_warshall(n, edges). Return an n by n matrix (a list of n lists) where entry [i][j] is the shortest distance from i to j, float('inf') when j is unreachable from i, and 0 on the diagonal. Assume there is no negative-weight cycle.
Algorithm:
Return the completed matrix. Earlier functions are provided.
def bellman_ford(n, edges, source):
dist = [float('inf')] * n
dist[source] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
def has_negative_cycle(n, edges):
dist = [0] * n
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges:
if dist[u] + w < dist[v]:
return True
return False
def bellman_ford_safe(n, edges, source):
dist = [float('inf')] * n
dist[source] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
neg = False
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
neg = True
break
return (dist, neg)
def floyd_warshall(n, edges):
"""Return an n x n matrix of all-pairs shortest distances."""
# TODO: seed diagonal and edges, then run the k-i-j triple loop.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
When you need distances between every pair of vertices, Floyd-Warshall handles negative edges in one compact triple loop.
Implement floyd_warshall(n, edges). Return an n by n matrix (a list of n lists) where entry [i][j] is the shortest distance from i to j, float('inf') when j is unreachable from i, and 0 on the diagonal. Assume there is no negative-weight cycle.
Algorithm:
Return the completed matrix. Earlier functions are provided.
Press Run Tests or ββ© to check your solution.