CodeBlanks Logo Icon CodeBlanks

Summary - Floyd-Warshall

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

solution.py
def shortest_distance(graph, src, dst):
    # Solve all pairs and return src→dst

Sample solution

solution.py
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

Question
dist = [row[:] for row in ____]
Answer
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

All lessons in Advanced