To work with a graph, a program has to answer one question again and again: who are the neighbours of this vertex? The way you store the graph decides how fast that answer comes. There are two standard ways.
Give every vertex a list of its neighbours. Vertex 1 above is joined to 0, 2 and 3, so its list is [0, 2, 3].
Building it from an edge list takes one pass. In an undirected graph each edge goes into both lists:
function buildGraph(n, edges) { const adj = Array.from({ length: n }, () => []); // one empty list per vertex for (const [u, v] of edges) { adj[u].push(v); // u lists v as a neighbour... adj[v].push(u); // ...and v lists u (leave this out for a directed graph) } return adj;}Watch each edge land in two lists. Try a directed-looking chain like [0,1] [1,2] [2,3].
Memory O(V + E) — one list per vertex, one entry per edge end. Listing a vertex's neighbours costs only as many steps as it has neighbours. This is the default choice, and almost every solution in this course uses it.
A weighted graph stores pairs instead: adj[u] holds [v, weight] for each edge out of u.
Use an n × n grid where matrix[u][v] is 1 when u and v are joined, 0 otherwise (or the edge's weight, for a weighted graph).
function buildMatrix(n, edges) { const matrix = Array.from({ length: n }, () => new Array(n).fill(0)); for (const [u, v] of edges) { matrix[u][v] = 1; // 1 means "u and v are joined" matrix[v][u] = 1; // both ways for an undirected graph } return matrix;}Many graph questions never mention a graph: they give you a grid. Every cell is a vertex, and its neighbours are the cells up, down, left and right of it. You don't build anything — you compute the neighbours on the spot:
const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // up, down, left, right function neighbours(rows, cols, r, c) { const out = []; for (const [dr, dc] of DIRS) { const nr = r + dr, nc = c + dc; if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) out.push([nr, nc]); // stay inside the grid } return out;}Every grid question in this course — islands, oranges, regions, mazes — starts with exactly this loop. Some questions also allow the 4 diagonal moves; then DIRS simply has 8 entries.