Skip to content
Visual explainer 2h 30m to learn 4 steps

Graph representations

Store directed, undirected and weighted graphs as adjacency lists, matrices and edge lists.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 31 of 54

In short

A graph is a set of vertices connected by edges, which may be directed, undirected or weighted. The representation you pick decides the cost of every later algorithm. Adjacency lists suit the sparse graphs common in practice, while adjacency matrices suit dense graphs and constant-time edge checks.

Explained simply

A graph is a way to draw relationships. The things are called vertices (or nodes), and the links between them are called edges. Cities and roads, people and friendships, web pages and links: all of these are graphs. Once a problem is a graph, a small set of well-known algorithms can solve it.

Edges come in a few flavours. An undirected edge works both ways, like a friendship. A directed edge points one way, like following someone on social media. A weighted edge carries a number, such as a distance, a price or a time.

A computer cannot see a drawing, so we must store the graph in memory. The most common way is an adjacency list: for every vertex, keep a list of its neighbours. Another way is an adjacency matrix: a big table where cell [u][v] says whether u links to v. A third way is a plain list of edges.

The choice matters because every later algorithm reads the graph again and again. Pick a storage that wastes memory or makes neighbour lookups slow, and even a good algorithm becomes slow. For most real problems the adjacency list is the right default.

Press Play on a diagram to walk through it one step at a time.

CompareRepresentations for V vertices and E edges
Adjacency list
  • Space O(V + E)
  • Iterate neighbours in O(degree)
  • Edge check O(degree)
  • Default for sparse graphs
Adjacency matrix
  • Space O(V^2)
  • Edge check O(1)
  • Iterate neighbours O(V)
  • Good for dense graphs
Edge list
  • Space O(E)
  • Simple to sort by weight
  • Used by Kruskal and Bellman-Ford
MapKinds of graphs you will meet
Graph
  • By direction
    • Undirected: friendships
    • Directed: links, follows
  • By edge cost
    • Unweighted: every edge costs 1
    • Weighted: distance, price, time
  • By cycles
    • Tree: connected, no cycles, V - 1 edges
    • DAG: directed, no cycles
  • By density
    • Sparse: E close to V
    • Dense: E close to V^2
  • By storage
    • Explicit: you build adj
    • Implicit: grids, puzzle states

In depth

The vocabulary you need

The degree of a vertex is the number of edges touching it. In a directed graph we split this into out-degree (edges leaving) and in-degree (edges arriving). A path is a sequence of vertices where each step follows an edge; a simple path never repeats a vertex. A cycle is a path that returns to its start.

Two counting facts are worth remembering. In an undirected graph, the degrees add up to exactly 2E, because every edge touches two ends. This is called the handshake lemma. And a simple graph (no self-loops, no repeated edges) with V vertices has at most V(V-1)/2 undirected edges, or V(V-1) directed ones. That maximum is why a dense graph has E close to V^2, and a sparse graph has E closer to V.

  • Sum of all degrees = 2E in an undirected graph
  • Sum of out-degrees = sum of in-degrees = E in a directed graph
  • A tree with V vertices has exactly V - 1 edges
  • Connected means every vertex can reach every other one

Adjacency lists in Python: three common shapes

If vertices are numbered 0 to n-1, a list of lists is the fastest and simplest: adj = [[] for _ in range(n)]. Every vertex has a slot, even one with no edges. If vertices are names like "DEL" or "alice", use a dict that maps each name to a list. For weighted graphs, store (neighbour, weight) tuples in the list.

When you often ask "is there an edge from u to v?", store neighbours in a set instead of a list. The check becomes O(1) on average instead of O(degree), at the cost of extra memory and no fixed order.

A common bug with collections.defaultdict: just reading adj[x] creates an empty entry for x. That is handy while building, but it can silently add vertices while you search. Also remember that vertices with no edges never appear in a dict built only from an edge list.

CompareWhich adjacency list shape to use
List of lists
  • Vertices are 0..n-1
  • Fastest access by index
  • Isolated vertices still have a slot
  • Edge check O(degree)
Dict of lists
  • Vertices have names
  • Only stores vertices you add
  • Keeps neighbour order
  • Edge check O(degree)
Dict of sets
  • Many edge-exists checks
  • Edge check O(1) on average
  • Drops duplicate edges
  • No stable neighbour order

Matrix versus list with real numbers

Picture a road network with 1,000,000 junctions and 2,500,000 roads. An adjacency matrix needs V^2 = 10^12 cells. Even at one bit per cell that is about 125 GB, so it simply does not fit. An adjacency list stores one entry per vertex plus two per undirected edge, about 6 million entries in total. That fits easily.

Now picture 300 cities where almost every pair has a direct flight. Here E is close to V^2 anyway, so the matrix costs about the same memory as a list, and it answers "is there a flight from A to B?" in O(1). Algorithms that touch every pair, like Floyd-Warshall for all-pairs shortest paths in O(V^3), are also natural on a matrix.

The cost that hurts most with a matrix is listing neighbours: you must scan a whole row, O(V), even if the vertex has only two neighbours. So BFS or DFS on a matrix costs O(V^2), not O(V + E).

  • Matrix: O(V^2) memory, BFS or DFS in O(V^2)
  • List: O(V + E) memory, BFS or DFS in O(V + E)
  • Rule of thumb: use a matrix only when V is a few thousand or less and the graph is dense

Grids are graphs you never build

A maze or a game map stored as rows of characters is already a graph. Each cell (r, c) is a vertex. Its neighbours are the cells up, down, left and right that are inside the grid and not walls. This is called an implicit graph: you compute neighbours on the fly instead of storing an adjacency list.

A grid with R rows and C columns has V = R x C vertices. With 4-direction moves, the number of undirected edges is R(C-1) + C(R-1), a bit less than 2RC. So BFS or DFS on a grid costs O(R x C). If you need a single number per cell, for example to use a list as a visited array, map (r, c) to r x C + c and back with divmod(i, C).

Some problems allow diagonal moves too. Then each cell has up to 8 neighbours. Always read the problem carefully: 4 or 8 directions changes both the answer and the edge count.

FlowGetting the neighbours of one grid cell
  1. 1
    Start at (r, c)

    The current vertex

  2. 2
    Try each direction

    (1,0), (-1,0), (0,1), (0,-1)

  3. 3
    Bounds check

    0 <= nr < R and 0 <= nc < C

  4. 4
    Wall check

    Skip blocked cells like '#'

  5. 5
    Yield neighbour

    The algorithm treats it as an edge

Turning problem input into a graph

Most problems hand you the graph as n plus an edge list, like edges = [[0, 1], [1, 2]]. Your first job is almost always the same three lines: create n empty lists, loop over the edges, and append. For an undirected graph append both ways; for a directed graph only u to v.

Check three details before you code. Are vertices numbered from 0 or from 1? If from 1, make n + 1 slots or subtract 1. Does [a, b] mean a points to b, or the reverse? Course schedule problems often list [course, prerequisite], so the edge goes from the prerequisite to the course. And can there be duplicate edges or self-loops? They rarely break traversal, but they change degree counts.

Some algorithms need the reverse graph, where every edge is flipped. Build it in the same loop: radj[v].append(u). It costs another O(V + E) memory and is used, for example, by Kosaraju's algorithm for strongly connected components.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Learn vertices, edges, degree and paths~40m
  2. 2
    Build adjacency lists with dicts~40m
  3. 3
    Compare adjacency matrix and list costs~40m
  4. 4
    Treat grids as implicit graphs~40m

Key points

  • Most traversal algorithms run in O(V + E) on adjacency lists.
  • Undirected edges are stored in both directions.
  • Grids are implicit graphs: neighbours are up, down, left and right.
  • Sparse means E is close to V; dense means E is close to V^2.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from collections import defaultdict

edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
adj = defaultdict(list)
for u, v in edges:            # undirected: store both ways
    adj[u].append(v)
    adj[v].append(u)

n = 4
matrix = [[0] * n for _ in range(n)]
for u, v in edges:
    matrix[u][v] = matrix[v][u] = 1

print(dict(adj), matrix[2][3])

A directed, weighted flight network

You get a list of flights as (from, to, hours). Step 1: since a flight from DEL to BOM does not mean one from BOM to DEL, store each edge only one way. Step 2: keep the hours with the neighbour as a tuple. Step 3: count in-degrees while building, because a city with in-degree 0 cannot be reached by any flight. The out-degrees add up to 4 and so do the in-degrees, matching E = 4.

python
from collections import defaultdict

flights = [("DEL", "BOM", 2), ("BOM", "BLR", 1.5),
           ("DEL", "BLR", 2.75), ("BLR", "DEL", 2.75)]
adj = defaultdict(list)
indeg = defaultdict(int)
for u, v, hours in flights:
    adj[u].append((v, hours))   # directed: one way only
    indeg[v] += 1

for city in sorted(set(adj) | set(indeg)):
    print(city, "out:", len(adj[city]), "in:", indeg[city])
# BLR out: 1 in: 2 / BOM out: 1 in: 1 / DEL out: 2 in: 1

Counting the edges of a grid without building it

A 3 x 4 grid has 12 cells. Step 1: write a neighbours generator that checks the bounds. Step 2: add up every cell's degree. Step 3: divide by 2 (the handshake lemma), because each undirected edge was counted from both ends. The result, 17, matches the formula R(C-1) + C(R-1) = 3 x 3 + 4 x 2.

python
def neighbours(r, c, rows, cols):
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < rows and 0 <= nc < cols:
            yield nr, nc

rows, cols = 3, 4
degree_sum = sum(len(list(neighbours(r, c, rows, cols)))
                 for r in range(rows) for c in range(cols))
print(degree_sum // 2)   # 17

Quick reference

  • adj = [[] for _ in range(n)]; never [[]] * n, which shares one list
  • Undirected edge: adj[u].append(v) and adj[v].append(u)
  • Weighted edge: adj[u].append((v, w))
  • Sum of degrees = 2E (undirected); a tree has V - 1 edges
  • Max edges in a simple graph: V(V-1)/2 undirected, V(V-1) directed
  • Grid cell (r, c) <-> index r * C + c; back with divmod(i, C)
  • Adjacency list traversal O(V + E); matrix traversal O(V^2)
  • Use a dict of sets when you need fast edge-exists checks

Common mistakes

  • Building a V x V matrix for a graph with a million vertices.
  • Adding only one direction for undirected edges.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An undirected graph has 12 edges. What is the sum of all vertex degrees?

Question 2

2What is the maximum number of edges in a simple undirected graph with 10 vertices?

Question 3

3Why is adj = [[]] * n a bug?

Question 4

4You run BFS on a graph stored as an adjacency matrix. What is the running time?

Question 5

5A grid has 50 rows and 40 columns with 4-direction moves. How many vertices does its graph have?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Given n = 5 and undirected edges [[0, 1], [1, 2], [2, 0], [3, 2]], build a list-of-lists adjacency list and print the degree of every vertex, including vertex 4.

  2. Exercise 2medium

    Write two functions: matrix_to_list(m) that turns a 0/1 adjacency matrix into an adjacency list, and reverse_graph(adj) that flips every edge of a directed graph.

  3. Exercise 3hard

    A grid uses '.' for open cells and '#' for walls. Build an explicit adjacency list over open cells only, using index r * cols + c, and return the number of undirected edges.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use an adjacency list or an adjacency matrix?
Use an adjacency list by default, because most real graphs are sparse and it costs O(V + E) memory. Use a matrix only for small, dense graphs or when you need O(1) edge checks.
Is a tree a graph?
Yes. A tree is a connected undirected graph with no cycles, and it always has exactly V - 1 edges.
Do I need a graph library like NetworkX for interviews?
No. Interviews expect you to build the adjacency list yourself with lists or dicts. NetworkX is great for analysis work, but it is much slower than plain lists for tight loops.
What is the difference between sparse and dense graphs?
A sparse graph has E on the order of V, like road maps. A dense graph has E close to V^2, where most pairs of vertices are connected.

Go deeper

ShareXLinkedInWhatsApp