DSAVisualiseData Structures & Algorithms Studio
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 JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

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.

Live snapshot

Current operation

Trace state
Ready 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

Java
ConnectedComponents.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1