Shortest Path in an Unweighted Graph
Problem statement
You are given an undirected, unweighted graph with n vertices numbered from 0 through n - 1. Each pair edges[i] = [u, v] represents an edge connecting vertices u and v.
Given vertices source and target, return the minimum number of edges on any path from source to target. Return -1 if target is unreachable from source.
Function
shortestPathLength(n: int, edges: int[][], source: int, target: int) → intExamples
Example 1
n = 5edges = [[0,1],[1,2],[0,3],[3,4],[4,2]]source = 0target = 2return = 2The path 0 -> 1 -> 2 uses two edges, and no one-edge path connects 0 to 2.
Example 2
n = 4edges = [[0,1],[2,3]]source = 0target = 3return = -1Vertices 0 and 3 belong to different connected components.
Example 3
n = 3edges = [[0,1]]source = 2target = 2return = 0A vertex has distance 0 from itself.
Constraints
1 ≤ n ≤ 10^5.0 ≤ edges.length ≤ 2 * 10^5.- Each edge contains two distinct vertices in the range
[0, n - 1]. - No undirected edge appears more than once.
0 ≤ source, target < n.