oneby7

Advanced Graphs Weighted shortest paths

484. Floyd-Warshall algorithm

Hard

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

510310123
dist
0589-1034-1-101-1-1-10
output

Input: dist = [[0, 5, -1, 10], [-1, 0, 3, -1], [-1, -1, 0, 1], [-1, -1, -1, 0]]

Output: [[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

000012
dist
000000000
output

Input: dist = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]]

Output: [[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

10⁶01
dist
010⁶-10
output

Input: dist = [[0, 1000000], [-1, 0]]

Output: [[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.

dist = [[0, -1, -1, 2], [-1, 0, -1, -1], [-1, 4, 0, -1], [-1, -1, 1, 0]]

Constraints

  • n == dist.length == dist[i].length
  • 1 ≤ n ≤ 300
  • dist[i][j] == -1 or 0 ≤ dist[i][j] ≤ 106
  • dist[i][i] == 0

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.