Data Structures & Algorithms / Module 8: Graphs

Topic 8.1

Representing graphs

Nodes, edges, and two ways to store them: neighbour lists or a table.

8 min · intermediate

Watch: the same map stored two ways: a list of each place's neighbours, or a full table of every pair.

BADCFE
  • moving now
  • being checked
Step 1 of 8

6 places (nodes) and 8 roads (edges). Roads go both ways. How do we store this in memory?

An adjacency list stores only the roads that exist. A matrix stores every pair, road or not.

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 listAdjacency matrix
MemoryV + E (nodes + edges)V²
Are A and B connected?Walk A's neighboursO(1)
All of A's neighboursAs many as it hasAlways 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

  1. A graph with 10,000 nodes, each with about 5 neighbours. Which uses less memory?

  2. What is the adjacency matrix good at?

  3. 'A follows B' on social media is best modelled as…

0 of 3 answered.