You are given an undirected graph with n nodes and a list of edges. Decide whether there is a path from the source node to the destination node.
DSA Animator › DSA Revision › Graph › Find if Path Exists in Graph
Remember: 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. The video solves Find if Path Exists in Graph (LeetCode 1971, Easy) with the BFS / Union Find pattern from the Graph topic, and you can replay every step in the interactive Find if Path Exists in Graph animation.
You are given an undirected graph with n nodes and a list of edges. Decide whether there is a path from the source node to the destination node.
For six nodes with edges 0 1, 0 2, 2 3, 3 5 and 1 4, a path from 0 to 5 exists: 0, 2, 3, 5. If the edge 3 5 were missing, node 5 could not be reached, and the answer would be false.
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.
Start with 0 in the queue, and mark it visited. Pop 0, and add its neighbours 1 and 2. Pop 1, and add its neighbour 4. Pop 2, and add its neighbour 3. Pop 4, which has no new neighbours, then pop 3, and add 5. 5 is the destination, so the answer is true.
In code, build the adjacency list with two entries per edge, because the graph is undirected. Use a boolean visited array, and a queue that starts with the source. Poll a node, return true if it is the destination, otherwise offer every unvisited neighbour. Return false when the queue is empty. Each node and each edge is handled once, so it is O of n plus e.
Remember: 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.