There is a bi-directional graph with n vertices labeled 0 to n-1. Given source and destination, return true if there is a valid path from source to destination.
n=3, edges=[[0,1],[1,2],[2,0]], source=0, destination=2trueparent[i]=i for all nodes(a,b): union(parent, a, b)find(parent,src)==find(parent,dst)Union-Find tracks connected components. After processing all edges, src and dst are in the same component iff they're connected. Path compression makes lookups near O(1).
Trying every possible path from the source can blow up on graphs with many cycles. We only need to know whether the destination is reachable, not the path itself.
First, turn the edge list into an adjacency list, so each node knows its neighbours. Then run a breadth first search from the source. Mark a node as visited when you add it to the queue, so no node is processed twice. If the destination is ever visited, the answer is true. If the queue runs empty first, the answer is false.
Reachability is a plain BFS or DFS with a visited set. Union find answers the same question by checking if both nodes share a root.
Run the animation above on your own input, or watch the 2:00 video explanation of Find if Path Exists in Graph with a dry run and Java code.