Module 9 · Graphs and Tries · Lesson 29 of 40

Graphs: things and connections

Vertices and edges, directed and weighted graphs, and how to store a graph with an adjacency list.

In this lesson · about 20 minutes

  • Use the words vertex, edge, neighbour, directed and weighted
  • Store a graph as an adjacency list (a dict of lists)
  • Compare an adjacency list with an adjacency matrix

A graph is a set of things and the connections between them. Cities and roads. People and friendships. Web pages and links. Trees are graphs too, just without loops.

WordMeaning
Vertex (or node)One thing: a city, a person
EdgeA connection between two vertices
NeighboursVertices joined directly by an edge
DegreeHow many edges touch a vertex
PathA route from one vertex to another along edges
CycleA path that comes back to where it started
ConnectedEvery vertex can reach every other one

We write V for the number of vertices and E for the number of edges.

Kinds of graphs

  • Undirected: edges go both ways (friendship).
  • Directed: edges have arrows, one way only (following someone online, a one-way street).
  • Weighted: each edge has a number, like a distance or a cost.
  • Unweighted: every edge counts the same.

Storing a graph

The most common way is an adjacency list: a dict where each vertex maps to a list of its neighbours.

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"],
}

The other way is an adjacency matrix: a V × V grid where matrix[i][j] is 1 if there is an edge from i to j.

Adjacency listAdjacency matrix
MemoryO(V + E)O(V²)
"Is there an edge A–B?"O(degree)O(1)
List all neighboursO(degree)O(V)
Best forMost real graphs (few edges)Small graphs with many edges

Try it: build a graph from a list of edges

Exercise

Build a directed graph

Write build(edges) that turns a list of directed edges (from, to) into an adjacency list dict. Every vertex that appears anywhere should be a key, even if it has no outgoing edges (give it an empty list).

Check your understanding0 of 3 correct

Question 1

1.Twitter-style 'following' (A follows B, but B may not follow A) is which kind of graph?

Question 2

2.A map of cities with road lengths is a…

Question 3

3.Memory for an adjacency list?

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.