Problem Description
Given an undirected graph with n nodes and an array of edges, determine the number of connected components in the graph.
Key Insights
- Use an adjacency list to represent the graph.
- A DFS (or BFS) traversal from an unvisited node will traverse an entire connected component.
- Each new DFS/BFS call from an unvisited node signals a separate connected component.
- Alternatively, the Union-Find data structure can be used to union connected nodes and count distinct sets.
Space and Time Complexity
Time Complexity: O(n + e), where n is the number of nodes and e is the number of edges. Space Complexity: O(n + e) due to the storage of the graph and tracking of visited nodes.
Solution
We solve the problem by iterating over each node and performing a DFS for any node that hasn't been visited. The DFS uses an iterative approach with a stack to traverse all nodes in a connected component. Each DFS initiation corresponds to one connected component. This method efficiently explores the graph using an adjacency list and marks nodes as visited to prevent redundant traversals.