Problem · Graph
Path Existence in an Undirected Graph
Learn this problemProblem statement
You are given an undirected graph with n vertices numbered from 0 to n - 1. The array edges contains one unordered pair [u, v] for each edge between vertices u and v.
Return true if a path connects source to destination. Otherwise, return false.
A vertex always has a path to itself, including an isolated vertex.
Function
validPath(n: int, edges: int[][], source: int, destination: int) → booleanExamples
Example 1
n = 3edges = [[0,1],[1,2],[2,0]]source = 0destination = 2return = trueThe edge between 0 and 2 directly connects the two vertices.
Example 2
n = 6edges = [[0,1],[0,2],[3,5],[5,4],[4,3]]source = 0destination = 5return = falseVertices 0 and 5 belong to different connected components.
Example 3
n = 1edges = []source = 0destination = 0return = trueThe source and destination are the same isolated vertex.
Constraints
1 <= n <= 200000.0 <= edges.length <= 200000.- Every edge contains two valid vertex numbers.
0 <= source, destination < n.- The graph may contain cycles, disconnected components, and repeated edges.