Advanced Graphs Weighted shortest paths
484. Floyd-Warshall algorithm
You are given a directed graph with n vertices, numbered from 0 to n - 1, as an n × n matrix dist.
The entry dist[i][j] is the weight of the edge from vertex i to vertex j, or -1 if there is no such
edge. An edge can be used only from i to j. Every dist[i][i] is 0.
The length of a path is the sum of the weights of its edges. Return an n × n matrix whose entry [i][j] is
the length of the shortest path from vertex i to vertex j, or -1 if no path leads from i to j. The
entry [i][i] is 0. You may change dist and return it.
Example 1
Input: dist = [[0, 5, -1, 10],
[-1, 0, 3, -1],
[-1, -1, 0, 1],
[-1, -1, -1, 0]]
[[0,5,8,9],[-1,0,3,4],[-1,-1,0,1],[-1,-1,-1,0]]Explanation: Vertex 0 reaches vertex 3 at 5 + 3 + 1 = 9 through vertices 1 and 2, which beats the direct edge of 10.
No edge leads back to a lower vertex, so every entry below the diagonal is -1.
Example 2
Input: dist = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]]
[[0,0,0],[0,0,0],[0,0,0]]Explanation: The edges 0 → 1, 1 → 2 and 2 → 0 all have weight 0. They form a cycle, so every vertex reaches every other one at length 0.
Example 3
Input: dist = [[0, 1000000], [-1, 0]]
[[0,1000000],[-1,0]]Explanation: The only edge leads from vertex 0 to vertex 1, so vertex 1 cannot reach vertex 0.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
n == dist.length == dist[i].length1 ≤ n ≤ 300dist[i][j] == -1or0 ≤ dist[i][j] ≤ 106dist[i][i] == 0
Clarifying questions
What you would ask an interviewer before writing any code.