Determine whether two vertices in an undirected graph are connected by any path.
Problem
You are given an undirected graph with n vertices labeled from 0 to n - 1, a list of edges, a source vertex source, and a destination vertex destination.
Return true if there exists any path from source to destination; otherwise return false.
A path may use any number of intermediate vertices, but it must follow the edges of the graph.
Notes
- The graph is undirected, so each edge can be used in both directions.
- You only need to determine reachability, not the actual path.
- Multiple edges and self-loops are not important for the core idea, but your solution should still behave correctly.
Input Format
n: number of verticesedges: list of undirected edges, where each edge is[u, v]source: starting vertexdestination: target vertex
Output Format
- Return
trueifdestinationis reachable fromsource, otherwise returnfalse.
Constraints
0 <= source, destination < n- The graph has
nvertices labeled0..n-1 edges[i] = [u, v]represents an undirected edge betweenuandvnandedges.lengthare expected to be within typical interview-sized limits for graph traversal
Hints
- Think in terms of reachability: if you can visit all nodes connected to
source, can you tell whetherdestinationis among them? - You may solve this with either graph traversal or a connectivity data structure.
Input Format
n: number of verticesedges: undirected edge list[[u1, v1], [u2, v2], ...]source: start vertexdestination: target vertex
Output Format
- Return a boolean value:
trueif a path exists, otherwisefalse.
Constraints
- Undirected graph
- Vertices are labeled from
0ton - 1 sourceanddestinationare valid vertex labels- Return reachability only; do not construct the path
Example 1
Input
n = 3 edges = [[0,1],[1,2],[2,0]] source = 0 destination = 2
Output
true
Explanation
There is a direct edge from 0 to 2, so a path exists.
Example 2
Input
n = 6 edges = [[0,1],[0,2],[3,5],[5,4],[4,3]] source = 0 destination = 5
Output
false
Explanation
Vertices 0 and 5 belong to different connected components, so no path exists.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.