Typorithm · medium

Connected Components

▷ Interactive algorithm labconnected-componentsgraph-algorithmsflood-fillvisited-setcomponents
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Connected Components

0%

Graph Algorithms

Flood-fill from every unvisited node; each new flood is one connected component.

A connected component is a maximal group of nodes reachable from one another.

Scanning all nodes, each unvisited one starts a DFS that marks its whole component.

The number of times you launch a fresh DFS equals the component count.

Preparing algorithm lab…
01

Build an undirected adjacency list.

02

DFS floods one whole component.

03

Each new flood adds one to the count.

function countComponents(n, edges) {
  const graph = Array.from({ length: n }, () => []);
  for (const [a, b] of edges) {
    graph[a].push(b);
    graph[b].push(a);
  }

  const visited = new Set();
  let count = 0;

  function explore(node) {
    visited.add(node);
    for (const next of graph[node]) {
      if (!visited.has(next)) explore(next);
    }
  }

  for (let node = 0; node < n; node += 1) {
    if (!visited.has(node)) {
      count += 1;
      explore(node);
    }
  }

  return count;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Adjacency list

Build an empty neighbor list for every node.

const graph = Array.from({ length: n }, () => [])

2. Both directions

An undirected edge connects both endpoints to each other.

graph[b].push(a)

3. Flood a region

DFS marks every node reachable from a starting node.

function explore(node)

4. New component

An unvisited node begins a brand-new component.

if (!visited.has(node))

5. Count it

Each new flood is one more connected component.

count += 1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Connected Components: Visual Walkthrough & Practice · Typorithm | ApplyDjinn