Problem · String
Shortest Path from Encoded Graph Edges
Learn this problemProblem statement
You are given an array edges describing an unweighted, undirected graph. Each entry has the exact form "u,v", where u and v are nonnegative decimal node labels.
Parse the edges and return the minimum number of edges on any path from source to target.
- Duplicate edges and self-loops may appear and do not change the answer.
- When
sourceequalstarget, return0. - When
targetis unreachable, return-1.
Function
shortestHopDistance(edges: String[], source: int, target: int) → intExamples
Example 1
edges = ["0,1","1,2","0,3","3,2"]source = 0target = 2return = 2Both 0 → 1 → 2 and 0 → 3 → 2 use two edges, so the shortest-hop distance is 2.
Example 2
edges = ["10,11","12,13"]source = 10target = 13return = -1The source and target belong to different connected components.
Constraints
0 <= edges.length <= 200000.- Every edge is exactly two decimal integers separated by one comma, with no spaces.
- Every node label,
source, andtargetis between0and1000000000.