Summary - Floyd-Warshall
- Algorithms course
- Advanced
- Lesson 28/56
- 4 min
Run Floyd-Warshall on a small graph in a mini task.
Summary - Floyd-Warshall
In this group you learned Floyd-Warshall, which finds shortest paths for all pairs. Adjacency matrix, triple loop and relaxation formula combine into the solution.
Now you will write a query function that brings all pieces together. This summary unites the group's concepts in a single piece of code.
Practice shortest_distance function
Write shortest_distance(graph, src, dst). Run Floyd-Warshall, return dist[src][dst]. Print 6 with print(shortest_distance(init_graph(), 0, 3)).
Starter code
def shortest_distance(graph, src, dst):
# Solve all pairs and return src→dstSample solution
def shortest_distance(graph, src, dst):
# Solve all pairs and return src→dst
n = len(graph)
dist = [row[:] for row in graph]
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist[src][dst]
print(shortest_distance(init_graph(), 0, 3))Expected output
6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the output of Floyd-Warshall?
- A single distance
- Edge weights
- A path list
- All-pairs distance matrix Correct answer
Explanation: The output is the all-pairs distance matrix.
2 Matrix copy
dist = [row[:] for row in ____]
dist = [row[:] for row in graph]
Explanation: graph is right.
3 Summary - Floyd-Warshall: match the terms
| Term | Meaning |
|---|---|
init_graph |
Graph |
relax_edge |
Relaxation |
floyd_warshall |
Triple loop |
dist |
Distance |