Graphs
Build a Graph as an Adjacency List
Represent an undirected graph as a map from each vertex to its list of
neighbours. For every edge (u, v), append v to adj[u] and u to
adj[v]. Neighbour lists keep insertion order so the graph is a stable,
deterministic fixture for the search lessons.
Algorithm
Basic Implementation
basic.js
const edges = [[1, 2], [1, 3], [2, 4], [3, 4], [4, 5], [5, 6]];
const adj = new Map();
for (const [u, v] of edges) {
if (!adj.has(u)) adj.set(u, []);
if (!adj.has(v)) adj.set(v, []);
adj.get(u).push(v);
adj.get(v).push(u);
}
const parts = [];
for (const [v, nbrs] of adj) {
parts.push(v + ": [" + nbrs.join(", ") + "]");
}
console.log("{" + parts.join(", ") + "}");
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- JavaScript: a
Mapkeyed by vertex preserves insertion order, and each entry is an array of neighbours appended in edge order. - The replay shows the adjacency map after each edge is added, matching the lesson spec.
adjacency list
Each edge adds two directed entries, one in each direction.