Problem Description
Given an undirected graph with n vertices labeled from 0 to n - 1 and an edge list representing bi-directional connections, determine if there exists a valid path from the source vertex to the destination vertex.
Key Insights
- The graph is undirected, meaning each edge can be traversed in both directions.
- Graph traversal algorithms such as DFS or BFS can be used to explore connectivity.
- Alternative approach using Union Find (Disjoint Set Union) is also effective for connectivity problems.
- Building an efficient adjacency list is key for handling large graphs.
Space and Time Complexity
Time Complexity: O(n + E), where n is the number of vertices and E is the number of edges.
Space Complexity: O(n + E), due to the storage of the adjacency list and auxiliary data structures (stack/queue, visited set).
Solution
We first construct an adjacency list from the provided list of edges. Then, we use a DFS (or alternatively, BFS) to traverse the graph starting from the source vertex. During the traversal, we mark each vertex as visited to avoid cycles. If we reach the destination, we return true; if the traversal completes without finding the destination, we return false.