Data Structures & Algorithms / Module 8: Graphs
Topic 8.1
Representing graphs
Nodes, edges, and two ways to store them: neighbour lists or a table.
Watch: the same map stored two ways: a list of each place's neighbours, or a full table of every pair.
- moving now
- being checked
Graphs are everywhere
- Maps: cities are nodes, roads are edges, road length is a weight.
- Social networks: people are nodes, friendships are edges. "Following" is a directed edge: A following B doesn't mean B follows A.
- Dependencies: npm packages, CI tasks, tables with foreign keys.
- Networks: servers and their connections, web pages and their links.
List or matrix
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Memory | V + E (nodes + edges) | V² |
| Are A and B connected? | Walk A's neighbours | O(1) |
| All of A's neighbours | As many as it has | Always V |
Real-world graphs are usually sparse: each node connects to only a few others. A million users with 200 friends each on average is about 200 million list entries. As a matrix, that's a trillion cells, almost all of them 0. A matrix only makes sense for small graphs, or ones where nearly every node connects to every other.
Code, for programmersAn adjacency list with a Map
const graph = new Map(); // node -> array of [neighbour, length]
function addRoad(a, b, length) {
if (!graph.has(a)) graph.set(a, []);
if (!graph.has(b)) graph.set(b, []);
graph.get(a).push([b, length]);
graph.get(b).push([a, length]); // leave this line out for a directed graph
}
addRoad("A", "B", 4);
addRoad("A", "C", 1);
graph.get("A"); // [["B", 4], ["C", 1]]Quiz
A graph with 10,000 nodes, each with about 5 neighbours. Which uses less memory?
What is the adjacency matrix good at?
'A follows B' on social media is best modelled as…
0 of 3 answered.