Data structures

Graphs, BFS and DFS, visualized.

Dots and the lines between them: roads, friendships, links. Then two ways to explore them: ring by ring with a queue, or deep first with a stack. A ghost walks every edge.

What is a graph?

A graph is a set of nodes (also called vertices) and edges that join pairs of them. Cities and roads. People and friendships. Web pages and links. Edges can be undirected (a road you can drive both ways) or directed (a one-way street, or “A follows B”). Some edges carry a number, a weight, like a distance; that is for a later lesson.

A tree is a connected graph with no cycles: there is exactly one path between any two nodes. The linked lists of lesson 1 were graphs all along: every node has one edge to the next.

UndirectedA–B works both ways.
DirectedA → B, but not back.
WeightedEach edge has a cost, like 5 km.
TreeNo cycles. Add the dotted edge and it stops being a tree.

01 — one item first

One node, then an edge.

Build a graph by hand. In Python the usual way to store one is a dict of lists: each node maps to the list of nodes it is joined to. That is an adjacency list.

Python

graph = {} # no nodes yet
graph['A'] = [] # one node, no edges
graph['B'] = ['A'] # B, joined to A…
graph['A'].append('B') # …and A to B: both ways
graph['C'] = ['B']
graph['B'].append('C')
graph['C'].append('A') # the edge that closes a loop
graph['A'].append('C')

02 — two ways to store it

Adjacency list vs adjacency matrix.

The same graph, written down two ways. The list keeps each node’s neighbours. The matrix keeps a grid of yes/no for every pair. Ask both the same questions.

Adjacency list

'A': ['B', 'C']
'B': ['A', 'D', 'E']
'C': ['A', 'F']
'D': ['B', 'G']
'E': ['B', 'F']
'F': ['C', 'E']
'G': ['D']

looks: 0 · stores 14

Adjacency matrix

ABCDEFG
A0110000
B1001100
C1000010
D0100001
E0100010
F0010100
G0001000

looks: 0 · stores 49

7 nodes, 7 edges. Pick a question.

Memory: the list stores each edge twice, 2 × E = 14 names. The matrix stores V × V = 49 cells, joined or not. For a million users with 100 friends each, that is 100 million list entries against a trillion matrix cells.

03 — breadth-first search

BFS: ring by ring, with a queue.

The ghost explores from A using the queue from lesson 2: the first node found is the first explored. So it finishes every node 1 edge away before any node 2 edges away.

Press Step to start at A.

Python · BFS

from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
while queue:
node = queue.popleft()
print(node)
for nxt in graph[node]:
if nxt not in visited:
visited.add(nxt)
queue.append(nxt) # one ring further out
Colour = distance from A. Dashed = found and waiting in the queue.

04 — depth-first search

DFS: deep first, with a stack.

Same graph, a stack instead of a queue. Here the stack is Python’s own call stack: dfs calls itself for each new neighbour, and each call waits, unfinished, on the stack until the calls above it return.

Press Step to call dfs on A.

Python · DFS

def dfs(graph, node, visited):
visited.add(node)
print(node)
for nxt in graph[node]:
if nxt not in visited:
dfs(graph, nxt, visited)
dfs(graph, 'A', set())
Strong orange = its call is still on the stack. Pale = finished and returned.

05 — your turn

Draw a graph, then search it.

Tap two nodes to join them, or tap a joined pair to cut the edge. Pick a start, then run BFS or DFS one step at a time.

Tap to

H has no edges yet. Join it to something, then run a search.

Python · BFS

from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
while queue:
node = queue.popleft()
print(node)
for nxt in graph[node]:
if nxt not in visited:
visited.add(nxt)
queue.append(nxt) # one ring further out

06 — the classic bug

The search that forgot where it had been.

A graph can have cycles; a linked list cannot. Leave out the visited set and the ghost walks round the loop for ever.

Four nodes in a loop. Each lists its clockwise neighbour first.

Buggy

def dfs(graph, node):
print(node)
for nxt in graph[node]:
dfs(graph, nxt) # never asks "been here?"
dfs(graph, 'A')

Fixed

def dfs(graph, node, visited):
visited.add(node)
print(node)
for nxt in graph[node]:
if nxt not in visited:
dfs(graph, nxt, visited)
dfs(graph, 'A', set())

07 — what BFS is for

Shortest path with BFS.

BFS reaches every node by a route with the fewest edges. Note who found each node (its parent), then walk the parents back from the goal.

From A to G. Tap another node to change the goal.

Python

from collections import deque
def shortest_path(graph, start, goal):
parent = {start: None} # doubles as visited
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
break
for nxt in graph[node]:
if nxt not in parent:
parent[nxt] = node
queue.append(nxt)
path, node = [], goal
while node is not None: # walk the parents back
path.append(node)
node = parent[node]
return path[::-1]
Only for unweighted graphs. With distances on the edges, the fewest edges may not be the shortest trip: that needs Dijkstra.

08 — spot them in the wild

Graph or not? Real examples.

Ask: are there things, and links between them that matter? Pick one for each, then read why.

A city map of streets and junctions

Who is friends with whom

A shopping list

Course prerequisites

Web pages and the links between them

A family tree

Last week’s temperatures

Flights between airports

09 — the boss level

Number of islands.

A favourite interview question in disguise. Each land square is a node, joined to the land squares above, below, left and right (not diagonal). Count the separate pieces. A square is named by (row, column), counting from 0 at the top left.

Scan every square. Each new land square starts an island: flood-fill it with BFS so it is never counted again.

Python

from collections import deque
def num_islands(grid):
rows, cols = len(grid), len(grid[0])
seen, count = set(), 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1 and (r, c) not in seen:
count += 1 # a new island
seen.add((r, c))
queue = deque([(r, c)])
while queue: # flood-fill it
cr, cc = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if (0 <= nr < rows and 0 <= nc < cols and
grid[nr][nc] == 1 and (nr, nc) not in seen):
seen.add((nr, nc))
queue.append((nr, nc))
return count
Time O(rows × cols): every square is scanned once and filled at most once. Tap squares to draw your own map.

10 — cheat sheet

BFS and DFS time complexity.

V is the number of nodes, E the number of edges. Both searches touch each node once and each edge from both ends: O(V + E).

JobCostIn Python
BFSO(V + E)memory O(V) for the queue and visitedcollections.deque: append and popleft(). A list’s pop(0) is O(n).
DFSO(V + E)memory O(V) for the stack and visitedRecursion is shortest. Python stops at about 1,000 nested calls (sys.getrecursionlimit()), so for deep graphs use a list as your own stack.
Shortest path, unweightedO(V + E)BFS plus a parent for each nodeparent = {start: None}
Adjacency list: memoryO(V + E)dict of lists
Adjacency list: are A and B joined?O(degree)scan A’s lista dict of sets makes it O(1)
Adjacency matrix: memoryO(V²)every pair, joined or notlist of lists
Adjacency matrix: are A and B joined?O(1)matrix[a][b]
Number of islandsO(rows × cols)BFS or DFS from each new land square
Back a lessonHeapsUp next: weighted graphs, coming soonAll data structures