Data Structures · Visualization
Graph: Connected Components
Graph
A connected component is a group of nodes that can all reach each other through some path, with no connection at all to nodes outside the group. Time: O(V + E). Space: O(V) for the visited set.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Connected Components
GraphA connected component is a group of nodes that can all reach each other through some path, with no connection at all to nodes outside the group. Finding all connected components means running BFS or DFS from every unvisited node, and each run discovers one full component, until every node has been visited.
How Connected Components Works
- Create an empty 'visited' set.
- For each node in the graph, if it hasn't been visited, start a new BFS or DFS from it.
- Mark every node reached during that traversal as visited and part of the current component.
- Move to the next unvisited node and repeat, starting a new component each time.
Connected Components Worked Example
Input: Graph with edges A-B, C-D (E is isolated)
- Start at A (unvisited): BFS/DFS reaches A, B → component 1 = {A, B}
- Start at C (unvisited): BFS/DFS reaches C, D → component 2 = {C, D}
- Start at E (unvisited): no edges → component 3 = {E}
Output: 3 components: {A,B}, {C,D}, {E}
Press ▶ Run to watch it step by step.
def connected_components(graph):
seen = set()
comps = []
for v in graph:
if v in seen:
continue
comp, stack = [], [v]
seen.add(v)
while stack:
cur = stack.pop()
comp.append(cur)
for nxt in graph[cur]:
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
comps.append(comp)
return comps
# example: componentsBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Connected Components Time & Space Complexity
When to Use Connected Components
- Finding isolated clusters or groups within a social network
- Identifying separate 'islands' in image processing
- Network reliability analysis (which nodes can still reach each other)
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.