Home
DSA Course
Data Structures
Connected Components
Connected Components
Learn how to find and count connected components in an undirected graph using BFS or DFS. Useful for social network analysis and image segmentation.
Ready to start
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.Intuition
Imagine a group of islands. You can walk anywhere on a single island, but you can't walk to another island without swimming.
Each island is a Connected Component.
Graph traversal algorithms like BFS or DFS can explore one entire island before moving to the next.
Concept
- Connected Component: A subgraph where every node is reachable from every other node in that subgraph.
- Traversal: To find all components, we iterate through every node. If a node hasn't been visited, it belongs to a new component. We then traverse (BFS/DFS) to find all nodes in that component.
How it Works
- Initialize
count = 0and avisitedset. - Iterate through all nodes
ifrom0toN-1. - If
node iis NOT visited:- Increment
count. - Start a traversal (BFS or DFS) from
node i. - Mark all reachable nodes as visited.
- Increment
- Return
count.
Step-by-Step Breakdown
Watch the visualization:
- White Node: Currently being visited.
- Colored Node: Assigned to a specific component. Different components have different colors.
When to Use
Use Connected Components when:
- Counting distinct groups in a social network (e.g., groups of friends).
- Image segmentation (grouping connected pixels).
- Finding isolated systems or unreachable servers in a network.
When NOT to Use
- Directed Graphs: For directed graphs, you typically look for Strongly Connected Components (SCC) or Weakly Connected Components, which require different algorithms (like Tarjan's or Kosaraju's).
How to Identify
Problems asking to "count groups", "count provinces", "number of islands", or "check path existence" often relate to connected components.
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
