Reading preferences
Concept

Representing Graphs

Describe connections between places using vertices, edges, and adjacency lists.

graph, vertex, edge, adjacency list, adjacency matrix

Places and paths

Imagine towns connected by roads. A graph describes things and their connections. Each town is a vertex (plural: vertices), and each road is an edge. A graph may contain a cycle, such as a road route that returns to its starting town. Unlike a tree, a graph can also have disconnected parts.

A --- B --- C     D

D is an isolated vertex: it exists even though no road touches it.

Why use it and where it helps

Graphs model roads, dependencies, and links between pages. They do not all mean the same thing: in a directed graph an edge A → B need not mean B → A. A weighted edge can carry a cost such as distance. The model must state what an edge and its direction mean before choosing an algorithm.

Two ways to store connections

An adjacency list stores neighbours for each vertex. For the undirected example above it is:

VertexNeighbours
AB
BA, C
CB
Dnone

Each undirected edge appears in both endpoint lists. A directed edge appears only in its source's outgoing list. An adjacency matrix instead has a row and column for every vertex; a cell says whether the corresponding edge exists. A weighted matrix needs a separate way to distinguish no edge from a zero-weight edge.

See the reasoning

Follow the example one step at a time

Build the adjacency lists for an undirected graph. This is a prepared teaching demonstration, not live code execution.

Start with four vertices

A: []   B: []   C: []   D: []

All four vertices exist, even before adding edges.

Python illustration

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

for vertex in graph:
    print(vertex, ":", graph[vertex])

Prepared output — not live execution:

A : ['B']
B : ['A', 'C']
C : ['B']
D : []

The example assumes every neighbour is also a key. The graph is undirected because both directions are explicitly present, not because Python makes them symmetric automatically.

Time, space, and common mistakes

For V vertices and E edges, an adjacency list for a simple graph uses O(V + E) space. Iterating over a vertex's neighbours takes time proportional to its number of neighbours. A full matrix uses O(V²) space and can check a given edge in O(1), but scanning a row takes O(V). A graph representation does not itself find a route; a search needs a rule for visiting and remembering nodes.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does an edge represent?
2. How is an undirected connection A–B recorded in an adjacency list?
3. What is an isolated vertex?
4. For V vertices how many cells does a full adjacency matrix have?

References and further reading