Problem 552355 · easy · Phase 05 Advanced Algorithms & Graphs

Distance Table for a Small Network

graphs · Floyd-Warshall · dynamic programming · matrix

A small office network has n switches labelled 0 .. n-1. Links are directed: links[i] = [u, v, ms] means packets can travel from u to v with a latency of ms milliseconds (ms >= 0). Parallel links are possible.

Return an n x n table t where t[u][v] is the smallest total latency from u to v, t[u][u] = 0, and -1 marks pairs with no route.

Examples

Input:  n = 3, links = [[0,1,5],[1,2,2],[0,2,9]]
Output: [[0, 5, 7], [-1, 0, 2], [-1, -1, 0]]
Explanation: 0 -> 1 -> 2 costs 7, cheaper than the direct link (9). Nothing leads back to 0.

Input:  n = 2, links = [[0,1,3],[0,1,1],[1,0,4]]
Output: [[0, 1], [4, 0]]

Constraints

  • 1 <= n <= 60, 0 <= len(links) <= 2000, 0 <= ms <= 10**6
  • Target O(n**3) time.

Goals

  • Initialise a distance matrix from a directed edge list
  • Apply the Floyd-Warshall triple loop in the correct order
  • Translate infinity back into a sentinel
Starting Python…