Design a graph data structure that supports adding directed weighted edges and answering shortest-path queries between nodes.
Implement a graph data structure that supports two operations:
The graph is dynamic: edges may be added over time, and each shortest-path query should reflect all updates made before that query.
If no path exists between the requested nodes, return -1.
Your implementation should be efficient enough for repeated updates and queries.
addEdge(u, v, w) adds a directed edge from u to v with weight w.shortestPath(node1, node2) returns the minimum total weight from node1 to node2, or -1 if unreachable.-1.1 <= n where n is the number of nodes.Example 1
Input
n = 4 operations = [ ["addEdge", 0, 1, 5], ["addEdge", 1, 2, 3], ["shortestPath", 0, 2], ["addEdge", 0, 2, 10], ["shortestPath", 0, 2], ["shortestPath", 2, 0] ]
Output
[8, 8, -1]
Explanation
The shortest path from 0 to 2 is 0 -> 1 -> 2 with total cost 8. Adding a direct edge 0 -> 2 with cost 10 does not improve it. There is no path from 2 back to 0.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.