Skip to contentKEEP THE CRAFTTHE SANCTUARY

Compute All-Pairs Shortest Paths

Find the cheapest path between every pair of nodes by allowing one more middle stop per round (Floyd-Warshall).

The problem

Implement all_pairs_shortest_paths(matrix). matrix is an n x n grid for a directed graph with n nodes: matrix[i][j] is the weight of the edge from i to j (weights are nonnegative), -1 means there is no such edge, and matrix[i][i] is 0. Return a new n x n grid whose entry [i][j] is the cost of the cheapest path from i to j, or -1 if j cannot be reached from i. Do not change matrix itself. For example, [[0, 3, -1], [-1, 0, 2], [1, -1, 0]] becomes [[0, 3, 5], [3, 0, 2], [1, 4, 0]]: node 0 reaches node 2 through node 1 for 3 + 2 = 5.

Starter code

def all_pairs_shortest_paths(matrix):
    pass

Public examples

  1. matrix = [[0, 3, -1], [-1, 0, 2], [1, -1, 0]]gives[[0, 3, 5], [3, 0, 2], [1, 4, 0]]
  2. matrix = [[0, -1], [-1, 0]]gives[[0, -1], [-1, 0]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.