A commuter rail map, the roads between cities in a maps app, and friendships on social media don't look alike at all. But their data has the same shape: points joined by lines, such as stations and tracks, cities and roads, people and friendships.
That shape is called a graph. The points are called nodes (another name is vertices), the same word as the nodes of a tree. A line that joins two nodes is called an edge. On a map, cities are nodes and roads are edges. On social media, people are nodes and friendships are edges.
Nodes, edges and neighbours
This is a map of four cities. Each line is one road:
London ----- Manchester
| |
Bristol ---- Birmingham
This map has 4 nodes (cities) and 4 edges (roads). In code, a graph is usually stored as an adjacency list: every node has one array, which holds the nodes joined directly to it. This is the adjacency list of the map above, written as an object:
const graph = {
London: ["Bristol", "Manchester"],
Bristol: ["London", "Birmingham"],
Birmingham: ["Bristol", "Manchester"],
Manchester: ["Birmingham", "London"],
};
console.log(graph["London"]); // ["Bristol", "Manchester"]
console.log(graph["London"].length); // 2
- A node's neighbours are the nodes joined to it directly by one edge. London's neighbours: Bristol and Manchester.
graph["London"]gives you all of London's neighbours right away, with no searching.- Degree is how many neighbours a node has, which is the length of its array. London's degree: 2.
- Every road is listed twice, once at each end: the road between London and Bristol appears in London's array and in Bristol's. So if you ask for Bristol's neighbours, London is on the list.
Going from London to Bristol, Birmingham, Manchester and back to London makes a cycle: a path that ends at the node where it started. The trees you already know are graphs too: all their nodes are connected (directly or through other nodes), and there's no cycle. A graph is freer: cycles are allowed, and a node can be joined to any other node.
Direction and weight
- Undirected: an edge works both ways. A road between A and B can be travelled in both directions, so A to B is the same as B to A. Friendship is an example.
- Directed: an edge has a direction. A → B (an edge from A to B) doesn't mean there is also B → A. Following on Instagram is an example: you follow someone, but they don't necessarily follow you back. In the adjacency list of a directed graph, each node only lists the edges leaving it.
- Weighted: every edge has a number (its weight), such as a distance in km. Unweighted: every edge counts the same.
Building it with a class and a Map
This code makes a Graph class that keeps the adjacency list in a Map. The name v is short for vertex, another name for a node.
class Graph {
constructor() {
this.adjacency = new Map(); // node → array of neighbours
}
addVertex(v) {
if (!this.adjacency.has(v)) this.adjacency.set(v, []);
}
addEdge(v1, v2) {
this.addVertex(v1); // a node that doesn't exist yet is created
this.addVertex(v2);
this.adjacency.get(v1).push(v2); // an undirected graph:
this.adjacency.get(v2).push(v1); // record it at both ends
}
}
const g = new Graph();
g.addEdge("London", "Bristol");
g.addEdge("London", "Manchester");
console.log(g.adjacency.get("London")); // ["Bristol", "Manchester"]
console.log(g.adjacency.get("Bristol")); // ["London"]
- A
Mapstores key and value pairs. Here the key is a node, and the value is its array of neighbours. addVertex(v)makes an empty array forvonly whenvisn't there yet, so neighbours already recorded aren't deleted.addEdge(v1, v2)first callsaddVertexfor both nodes. Then it pushesv2into the array ofv1, andv1into the array ofv2. The order of the neighbours follows the orderaddEdgewas called in.
Adjacency list or adjacency matrix?
Another way to store a graph is an adjacency matrix: a table (a 2D array) with one row and one column for each node. The cell in row A, column B holds 1 if there's an edge between A and B, and 0 if there isn't. Checking "is there an edge between A and B?" only reads one cell, so it's O(1). But the size of the table is always the number of nodes times the number of nodes, even when there are few edges: 1,000 nodes need 1,000,000 cells. An adjacency list only stores the edges that actually exist, so it uses far less memory for a graph with few edges (a sparse graph). Pick the adjacency list unless almost every node is joined to almost every other node.
⚠️ Edges recorded at one end only, and nodes not yet added
- Forgetting the second end. In an undirected graph,
addEdgehas to push into both arrays. If it pushes into only one, the edge is missing from the array of the node at the other end. addVertexoverwriting.this.adjacency.set(v, [])without ahascheck deletes the neighbours already recorded.- A node that isn't registered. For a node that doesn't exist yet,
this.adjacency.get(v)givesundefined, and.pushonundefinedis an error right away. So calladdVertexinsideaddEdge. - A cycle makes a search go on forever. Walking through a graph (visiting its nodes one by one along the edges) is the next lesson. While you walk, keep track of the nodes you've visited, because a cycle can bring you back to the same place over and over.
TL;DR: A graph is points (nodes) joined by lines (edges). A node's neighbours are the nodes joined to it directly by one edge, and its degree is how many neighbours it has. An adjacency list keeps an array of neighbours for every node, for example in a Map. An undirected graph (an edge works both ways) records each edge at both ends. A directed graph (an edge has a direction) records it only at the node the edge leaves from. An adjacency matrix (a table of 1s and 0s) always has as many cells as the number of nodes times the number of nodes. So an adjacency list uses less memory for a graph with few edges.
⚡ Nodes, edges and neighbours
Write:
const graph = {
London: ["Bristol", "Manchester"],
Bristol: ["London", "Birmingham"],
Birmingham: ["Bristol", "Manchester"],
Manchester: ["Birmingham", "London"],
};
console.log(graph["London"].length); // 2
Meaning: A graph is points (nodes, the same word as in trees) joined by lines (edges). Here the nodes are cities, and the edges are roads. An adjacency list keeps an array of neighbours for every node. A neighbour is a node joined directly by one edge: London's neighbours are Bristol and Manchester. The degree is how many neighbours a node has, which is the length of its array.
⚡ Direction and weight
Guess first: in a directed graph, an edge has a direction. In an undirected graph, an edge works both ways. You follow someone on Instagram. Is that graph directed or undirected?
Directed. You follow them, but they don't necessarily follow you back. So A → B (an edge from A to B) doesn't mean there is also B → A. Friendship is an example of an undirected graph.
Meaning: In an adjacency list, an undirected graph records each edge at both ends. A directed graph records it only at the node the edge leaves from. Weighted means every edge has a number, such as a distance in km.
⚡ Record it at both ends
Write:
addEdge(v1, v2) {
this.addVertex(v1); // a node that doesn't exist yet is created
this.addVertex(v2);
this.adjacency.get(v1).push(v2); // an undirected graph:
this.adjacency.get(v2).push(v1); // record it at both ends
}
Meaning: addEdge is a method of the Graph class (this means the graph in use). this.adjacency is a Map: its keys are nodes, its values are arrays of neighbours. After addVertex, v2 is recorded in the array of v1, and v1 in the array of v2. If only one end is recorded, the edge is missing from the array of the node at the other end. An adjacency list only stores the edges that exist. So for a graph with few edges, it uses less memory than an adjacency matrix (a table with one row and one column for each node).