Graphs & Connectivity Hard
Graph Connected Components
An undirected graph's connected components are found by scanning vertices and launching recursive depth-first search from each unmarked vertex.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(V + E)
AverageO(V + E)
WorstO(V + E)
SpaceO(V + E) graph storage and up to O(V) recursive stack
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Count the connected components of the input graph, including isolated vertices, while preserving the source's adjacency insertion order.
- The graph is undirected, so each addEdge call appends both directions; a self-loop is appended twice to the same list.
- The outer loop must include isolated vertices, which each add one component.
- Mark a vertex before recursively visiting its neighbors to stop cycles and parallel edges from repeating work.
- DFS follows adjacency insertion order, but the final component count is independent of that order.
- The source Graph class assumes valid indices; this lesson validates endpoints and bounds input to 20 vertices and 48 edges so traces stay finite.
Algorithm code
JavaConnectedComponents.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1