Home
DSA Visualizer
Data Structures
Connected Components
Connected Components Visualization
Connected components are the separate groups of vertices in an undirected graph, found and counted with BFS or DFS. They are useful for social network analysis and image segmentation. Step through it in the interactive Connected Components visualization below.
NEW COMPONENT
Components found: 1
Not yet reached
A has not been reached by any earlier search. It opens component #1.
Next
B is reachable from A, so it belongs to component #1 too.
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 Connected Components 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.
Connected Components Visualization, Step by Step
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), which need their own algorithms (Tarjan's or Kosaraju's). Weakly Connected Components are simpler: ignore edge directions and run this same traversal.
How to Identify
Problems asking to "count groups", "count provinces", "number of islands", or "check path existence" often relate to connected components.
Practice it on interview problems
LeetCode problems solved with the Graphs (Topological Sort) pattern, each with a step-by-step visualizer:
All Graphs (Topological Sort) problemsApplying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
