Menu
CoddyTech

Floyd Warshall Algorithm

A directed graph with n nodes, numbered 0 to n-1, is given as an n by n matrix: matrix[i][j] is the weight of the edge from node i to node j, or -1 when there is none, and matrix[i][i] is 0. A path's length is the sum of its edge weights.

Return an n by n matrix whose entry [i][j] is the length of the shortest path from node i to node j, or -1 when node j cannot be reached from node i.

Function

shortestDistances(matrix: integer-2d-array) → integer-2d-array
matrixinteger-2d-array
the edge weights: matrix[i][j] is the weight of the edge from i to j, or -1 when there is none
Returnsinteger-2d-array
the shortest distance for every pair of nodes, -1 where there is no path

Constraints

  • 1 ≤ n ≤ 100, where n = matrix.length = matrix[i].length
  • matrix[i][i] = 0
  • For i ≠ j, matrix[i][j] is -1 (no edge) or 0 ≤ matrix[i][j] ≤ 1000.
  • Edges are one way: matrix[i][j] and matrix[j][i] are independent.

Examples

Input
matrix = [[0, 4, 11, -1], [-1, 0, 2, 9], [1, -1, 0, 3], [-1, -1, -1, 0]]
Output
[[0, 4, 6, 9], [3, 0, 2, 5], [1, 5, 0, 3], [-1, -1, -1, 0]]
Explanation
Through node 1, node 0 reaches node 2 for 6 instead of 11, and node 3 for 9. Node 1 reaches node 0 through node 2 for 3. Nothing leaves node 3, so its row is -1 off the diagonal.
challenge icon

Follow-up

After you build the table, one edge gets cheaper. Can you update every distance in O(n²) instead of running the O(n³) loops again?

Reset code
def shortestDistances(matrix):
    # Write code here

Test #1

Test #2

Argument

matrix = [[0, 4, 11, -1], [-1, 0, 2, 9], [1, -1, 0, 3], [-1, -1, -1, 0]]

Expected Output

[[0, 4, 6, 9], [3, 0, 2, 5], [1, 5, 0, 3], [-1, -1, -1, 0]]