Dijkstra · Medium
A service-routing graph assigns a non-negative cost to each directed connection. The routing tool needs the least total cost between two selected nodes. Direct links may be more expensive than multi-step routes and parallel links may have different costs.
Return the minimum sum of edge weights from source to target or null when no valid route connects them.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer, edges: [integer, integer, integer][], source: integer, target: integer }
Fields
- n is the node count and edges contains directed [from,to,weight] triples. Parallel edges are distinct input entries; self-loops are allowed.
- All weights are non-negative integers unless the task explicitly requires positive weights.
- source is the starting node. source = -1 means no starting node and yields no reachable nodes.
- target is the destination node. target = -1 means no destination and yields no route.
Output
Return value
- Return the minimum numeric cost, not a path. Valid equal endpoints have cost zero.
- Zero-weight links are valid. Unreachable or missing endpoints produce null.
Constraints
- 0 <= n <= 50000; 0 <= edges.length <= 200000; endpoints are valid node labels; 0 <= weight <= 1000000.
- source and target, when used, are either -1 or valid node labels. All distance and slack results fit a safe JSON integer.
Examples
Example 1
{
"edges": [
[
0,
2,
9
],
[
0,
1,
2
],
[
1,
2,
3
]
],
"n": 3,
"source": 0,
"target": 2
}Returns
5Example 2
{
"edges": [
[
0,
1,
0
]
],
"n": 2,
"source": 0,
"target": 1
}Returns
0Required complexity
O(n + m log(m + 1)) time and O(n + m) auxiliary space