Shortest path · Medium
A routing map models each handoff as one directed edge with equal cost. A request must reach a destination using as few handoffs as possible. The result should distinguish an already-arrived request from a destination that cannot be reached.
Return the minimum number of directed edges from source to target or null if either endpoint is missing or the target is unreachable.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer, edges: [integer, integer][], source: integer, target: integer }
Fields
- n is the number of nodes labeled 0 through n-1. edges is an array of directed [from,to] pairs.
- Parallel edges and self-loops are allowed. For an undirected connection supply both directions.
- 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 an integer edge count, not a node count or route. A valid source equal to target returns zero.
- Return null when no route exists; zero is not an absence marker.
Constraints
- 0 <= n <= 100000; 0 <= edges.length <= 200000; every endpoint is a valid node label.
- source and target, when used, are either -1 or valid node labels. Empty graphs use -1.
Examples
Example 1
{
"edges": [
[
0,
1
],
[
1,
2
],
[
2,
3
],
[
0,
3
]
],
"n": 4,
"source": 0,
"target": 3
}Returns
1Example 2
{
"edges": [],
"n": 1,
"source": 0,
"target": 0
}Returns
0Required complexity
O(n + m) time and O(n + m) space including adjacency