All pairs
- Algorithms course
- Advanced
- Lesson 25/56
- 4 min
Shortest path between every pair of vertices.
All pairs
The Floyd-Warshall algorithm finds the shortest paths between all pairs of nodes in a graph in one go. The output is a distance matrix.
It returns results for all pairs, not just a single source. This is useful in dense graph problems.
Distance matrix
The graph is represented as an n×n adjacency matrix. graph[i][j] is the direct edge weight from i to j; if no edge, 999 (infinity) is used.
The diagonal is zero: graph[i][i] = 0. A triple loop runs on the matrix to compute the shortest paths.
Practice init_graph function
Write init_graph(). Return the 4×4 adjacency matrix. Print it with print(init_graph()).
Starter code
def init_graph():
# Return adjacency matrixSample solution
def init_graph():
# Return adjacency matrix
return [[0, 3, 999, 7], [999, 0, 1, 999], [999, 999, 0, 2], [999, 4, 999, 0]]
print(init_graph())Expected output
[[0, 3, 999, 7], [999, 0, 1, 999], [999, 999, 0, 2], [999, 4, 999, 0]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many node pairs does Floyd-Warshall solve?
- All pairs Correct answer
- Single source
- Only one pair
- Only neighbors
Explanation: Floyd-Warshall solves all pairs.
2 Infinity value
graph[i][j] = ____ (if no edge)
graph[i][j] = 999 (if no edge)
Explanation: 999 is right.
3 All pairs: match the terms
| Term | Meaning |
|---|---|
graph[i][i] |
0 |
graph[i][j] |
Edge |
999 |
Infinity |
n×n |
Size |