1. Adjacency list
Build an empty neighbor list for every node.
const graph = Array.from({ length: n }, () => [])Typorithm · medium
Step 1 of 8 · intro card
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.
Build an undirected adjacency list.
DFS floods one whole component.
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;
}Connect each part of the code to the concept before you type.
Build an empty neighbor list for every node.
const graph = Array.from({ length: n }, () => [])An undirected edge connects both endpoints to each other.
graph[b].push(a)DFS marks every node reachable from a starting node.
function explore(node)An unvisited node begins a brand-new component.
if (!visited.has(node))Each new flood is one more connected component.
count += 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state