Shortest Distance in a Graph
Problem statement
You are given an undirected, unweighted graph with n vertices labeled from 0 through n - 1. Each pair [u, v] in edges connects vertices u and v in both directions.
Return the minimum number of edges in a path from start to target. Return -1 if no such path exists.
- Every edge takes one step to traverse.
- If
startequalstarget, return0. - The graph may be disconnected or contain cycles. Duplicate edges and self-loops are allowed; they do not create a shorter route.
- Return only the minimum distance, not the sequence of vertices.
Function
shortestDistance(n: int, edges: int[][], start: int, target: int) → intExamples
Example 1
n = 6edges = [[0,1],[1,2],[2,5],[0,3],[3,5],[3,4]]start = 0target = 5return = 2The path 0 -> 3 -> 5 uses two edges. No edge connects 0 directly to 5, so a one-edge path is impossible.
Example 2
n = 5edges = [[0,1],[1,2],[3,4]]start = 0target = 4return = -1Vertices 0 and 4 belong to different connected components, so the result is -1.
Example 3
n = 3edges = [[0,1]]start = 2target = 2return = 0The start is already the target. No edge needs to be traversed, even though vertex 2 is isolated.
Constraints
1 <= n <= 200000 <= edges.length <= 100000- Every edge contains exactly two vertex labels.
- For every edge
[u, v],0 <= u, v < n. 0 <= start, target < n