All-Pairs Shortest Path Queries

Given a small weighted graph and multiple source-target queries, return the shortest distance for each query. Pattern focus: Floyd-Warshall. Precompute all-pairs shortest paths, then answer every query in O(1).

Input Format

n = node count, edges = weighted undirected or directed edges as specified in the problem, queries = [u, v] pairs

Output Format

distance for each query, or -1 if unreachable

Constraints

  • 1 <= n <= 100
  • 1 <= edges.length <= 10^4
  • 1 <= queries.length <= 10^4

Examples

Example 1:

Input:

n = 4
edges = [[0,1,3],[1,2,1],[2,3,2],[0,3,10]]
queries = [[0,3],[0,2],[1,3]]

Output:

[6,4,3]

Explanation:

The indirect routes are cheaper than some direct edges.

Example 2:

Input:

n = 3
edges = [[0,1,5]]
queries = [[0,2],[1,0]]

Output:

[-1,5]

Explanation:

Unreachable pairs return -1.

Example 3:

Input:

n = 2
edges = [[0,1,7]]
queries = [[0,1],[1,0]]

Output:

[7,7]

Explanation:

Symmetric distances are the same in an undirected graph.

Loading...
All-Pairs Shortest Path Queries - Shortest Path