A graph is a way to describe things that are connected to each other. Each thing is called a node (a point), and a connection between two nodes is called an edge (a line). The easiest example is a map: the towns are nodes, and the roads are edges. This lesson is about storing a graph in code, so that algorithms like BFS, DFS and Dijkstra, which you will learn later, can work with it.
Adjacency list: each town keeps its neighbours
There are four towns: A, B, C, D. The roads are A-B, B-C, C-D and D-A, forming a square. Every road can be used in both directions, so this graph is undirected: if A is joined to B, B is also joined to A. Two towns joined by one road are called neighbours. We write the roads down one by one, in each town's list of neighbours:
| Road | What gets written down |
|---|---|
| A-B | B goes in A's list, A goes in B's list |
| A-D | D goes in A's list, A goes in D's list |
| B-C | C goes in B's list, B goes in C's list |
| C-D | D goes in C's list, C goes in D's list |
The result, written as a JavaScript object (a set of keys, each with a value):
const graph = {
A: ["B", "D"],
B: ["A", "C"],
C: ["B", "D"],
D: ["A", "C"],
};
console.log(graph.A); // ["B", "D"]
console.log(graph.A.includes("C")); // false
- This is an adjacency list (a list of neighbours): each key is one town, and its value is an array of that town's neighbours.
graph.Agives you all of A's neighbours right away.graph.A.includes("C")checks "is A joined directly to C?" by checking A's list one by one. The answer isfalse: from A to C you have to go through B or D.- Each road is written down twice, once at each end, because the graph is undirected.
Adjacency matrix: a table of connections
A second way to store the same graph is a table of numbers, with one row and one column for each town:
const nodes = ["A", "B", "C", "D"];
const matrix = [
[0, 1, 0, 1], // A
[1, 0, 1, 0], // B
[0, 1, 0, 1], // C
[1, 0, 1, 0], // D
];
console.log(matrix[0][1]); // 1: A is joined to B
console.log(matrix[0][2]); // 0: A is not joined to C
An adjacency matrix is a V × V table, where V is the number of nodes. Rows and columns follow the order of nodes: A is index 0, B index 1, C index 2, D index 3. matrix[i][j] is the value in row i, column j. It is 1 when nodes i and j are joined, and 0 when they aren't. The diagonal, the cells whose row and column numbers are the same (matrix[0][0], matrix[1][1], ...), is all 0, because there's no road from a town to itself. If a node has an edge to itself (a self-loop), that node's diagonal cell holds 1. In an undirected graph, the matrix is symmetric: matrix[i][j] always equals matrix[j][i].
A directed graph has one-way connections, like following someone on social media: A following B doesn't mean B follows A. In an adjacency list, a connection from A to B is written down in A's list only. In a matrix, only matrix[a][b] (from a to b) becomes 1, so the matrix is no longer symmetric. When roads have a length (a weight), the list keeps [neighbour, weight] pairs, for example A: [["B", 4], ["D", 7]].
Nodes as numbers
Nodes are often just numbered 0 to n - 1, where n is the number of nodes (the same as V). The adjacency list then becomes an array of arrays, and the index in the outer array is the node's number. For example, [[1, 2], [0, 2], [0, 1, 3], [2]] means the neighbours of node 0 are 1 and 2, and the only neighbour of node 3 is 2.
This code makes a matrix for 3 nodes, records one road, then gets the neighbours of node 2:
const n = 3;
const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
matrix[0][2] = 1; // road 0-2...
matrix[2][0] = 1; // ...written on both sides
console.log(matrix[0].join(",")); // 0,0,1
const neighbours = [];
for (let v = 0; v < n; v++) {
if (matrix[2][v] === 1) neighbours.push(v);
}
console.log(neighbours); // [0]
Array.from({ length: n }, () => new Array(n).fill(0))makes n rows, and each row is a new array holding n zeros.- In the exercise, you turn a list into a matrix: for each node
uand each of its neighboursv, set bothmatrix[u][v]andmatrix[v][u]to 1. - In the exercise, you also turn a matrix into a list: for each row, collect the indexes of the columns that hold 1, from left to right. That way they come out smallest first. The
forloop in that code does this for row 2. join(",")joins an array's items into text:[0, 0, 1]becomes0,0,1.
List or matrix?
Big-O says how fast the number of steps grows as the data grows. In a graph, the data is measured with two numbers: V is the number of nodes, and E the number of edges. O(1) means the steps stay the same, however many nodes there are. O(V) means that if the nodes double, the steps roughly double.
| Job | Adjacency list | Adjacency matrix |
|---|---|---|
| Check "is i joined to j?" | go through i's neighbours | O(1), straight to matrix[i][j] |
| Get every neighbour of i | the list is right there | go through a whole row, O(V) |
| Memory | O(V + E): one list per node, each edge written down 2 times | O(V²), that is always V × V cells |
Most real graphs are sparse: they have few edges compared with every pair of nodes that could be joined. Store 10,000 towns with 50,000 roads as a matrix, and how many cells does it take? 10,000 × 10,000 = 100 million cells, while a list holds only about 100,000 entries (50,000 roads × 2). So the usual choice is an adjacency list. A matrix suits a small graph where nearly every pair of nodes is joined, or when you often ask "are i and j joined?". There is also a third form, an edge list, which only keeps a list of edges, for example [["A", "B"], ["A", "D"], ...]. An edge list suits algorithms that handle the edges one by one, like Kruskal in the Minimum Spanning Tree lesson later.
⚠️ Recording slips that make your graph lie
- Writing a road down only one way. In an undirected graph, one road fills two cells,
matrix[u][v]andmatrix[v][u], and goes into two neighbour lists. new Array(n).fill(new Array(n).fill(0)).fillputs one and the same array in every row. So changing one cell changes that cell in every row. UseArray.fromso each row is a new array.- 0 in a weighted matrix. When cells hold road lengths, 0 could mean "no road" or "a road of length 0". For "no road", fill the cell with
Infinity.
TL;DR: A graph is made of nodes (points, like towns) and edges (connections, like roads). An adjacency list keeps each node's neighbours, the nodes joined directly to it. It saves memory and gives all neighbours fast, so it's the usual choice. An adjacency matrix is a V × V table (V = the number of nodes) of 1s (joined) and 0s (not joined). Checking one connection is just matrix[i][j], O(1), but the table always takes V × V cells. An undirected graph (connections work both ways) is written down from both ends, so its matrix is symmetric. A directed graph (connections go one way) is written down only once. The matrix diagonal (the cells from a node to itself) holds 0, unless there is a self-loop: an edge from a node to itself.
⚡ Adjacency list: each town keeps its neighbours
Write:
const graph = {
A: ["B", "D"],
B: ["A", "C"],
C: ["B", "D"],
D: ["A", "C"],
};
console.log(graph.A); // ["B", "D"]
Meaning: A graph is nodes (points) joined by edges (lines). Here the nodes are four towns, and the edges are the roads between them. This way of storing it is called an adjacency list: each key is one town, and its value is an array of that town's neighbours, the towns joined directly by one road. The graph is undirected (every road can be used in both directions), so each road is written down twice, once at each end.
⚡ Adjacency matrix: a table of connections
Write:
const matrix = [
[0, 1, 0, 1], // A
[1, 0, 1, 0], // B
[0, 1, 0, 1], // C
[1, 0, 1, 0], // D
];
console.log(matrix[0][1]); // 1: A is joined to B
Meaning: An adjacency matrix is a V × V table, where V is the number of nodes. Rows and columns 0 to 3 are A to D. matrix[i][j] (row i, column j) is 1 when i and j are joined, and 0 when they aren't. Checking one connection is O(1). In this matrix, the diagonal (the cells from a node to itself) is all 0. In an undirected graph the matrix is symmetric: matrix[i][j] equals matrix[j][i].
⚡ List or matrix?
Guess first: store 10,000 towns with 50,000 roads as a matrix. How many cells does it take?
100 million cells (10,000 × 10,000), while a list holds only about 100,000 entries.
Meaning: Most real graphs are sparse: they have few edges compared with every pair of nodes that could be joined. So the usual choice is an adjacency list. A matrix suits a small graph where nearly every pair of nodes is joined, or when you often ask "are i and j joined?".