Lesson 19 of 40Trees and graphs
Graphs
Model problems as nodes and edges, then explore them with BFS, DFS, topological sort and Dijkstra.
Friends on a social network, roads between cities, packages that depend on other packages, cells in a maze: all of these are graphs. When npm install decides what order to install things in, or a maps app finds a route, a graph algorithm is doing the work.
Graphs look intimidating, but most problems use just two walks (breadth-first and depth-first) plus a visited set. You already know both from trees. A tree is simply a graph with no cycles and one root.
Vertices, edges, and how to store them
A graph is a set of vertices (also called nodes) joined by edges.
- Undirected: an edge goes both ways. Friendship: if Ada knows Sam, Sam knows Ada.
- Directed: an edge has an arrow. Following on social media, or "course A must come before course B".
- Weighted: each edge has a number, such as a distance or a cost.
- A cycle is a path that returns to where it started. A directed graph with no cycles is a DAG (directed acyclic graph).
There are two common ways to store a graph:
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Shape | { "A": ["B", "C"], ... } | V × V grid of 0/1 (or weights) |
| Memory | O(V + E) | O(V²) |
| "Is A linked to B?" | O(degree of A) | O(1) |
| "List A's neighbours" | O(degree of A) | O(V) |
| Use when | Almost always (real graphs are sparse) | Dense graphs, or tiny fixed V |
V is the number of vertices and E the number of edges. Interview problems usually hand you an edge list like [[0, 1], [1, 2]]; your first step is to turn it into an adjacency list.
from collections import defaultdict
edges = [["A", "B"], ["A", "C"], ["B", "D"], ["C", "D"], ["D", "E"]]
graph = defaultdict(list)
for a, b in edges:
graph[a].append(b)
graph[b].append(a) # undirected: add both directionsBreadth-first search
BFS explores in rings: first the start, then everything one edge away, then everything two edges away. It uses a queue, exactly like level-order traversal of a tree. The one new thing is a visited set, because graphs can have cycles and you must not process a node twice.
Because BFS reaches nodes in order of distance, the first time it reaches a node is along a shortest path (counting edges). That makes it the tool for shortest paths in unweighted graphs.
Start at A, distance 0. Mark it visited when it enters the queue.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.BFS visits each vertex once and looks at each edge once (twice if undirected), so it is O(V + E) time and O(V) space.
Depth-first search
DFS follows one path as far as it can, then backs up and tries the next branch. It is naturally recursive, like tree traversal, again with a visited set. DFS does not find shortest paths, but it is the simplest way to answer "can I reach X?", "how many connected pieces are there?" and "is there a cycle?".
Visit A (order 1). Go to its first unvisited neighbour, B.
def dfs(graph, node, visited):
visited.add(node)
for nxt in graph[node]:
if nxt not in visited:
dfs(graph, nxt, visited)Same cost as BFS: O(V + E). One caution: Python's default recursion limit is 1,000 frames, so on a long path (say, a 300×300 grid snake) recursive DFS can raise RecursionError. Switch to an explicit stack, or use BFS.
Grids are graphs
Many interview graphs are hidden in a grid. Each cell is a vertex, and its up, down, left and right neighbours are its edges. You never build an adjacency list; you compute neighbours with four (dr, dc) offsets and a bounds check.
Number of islands: given a grid of "1" (land) and "0" (water), count connected pieces of land. Scan every cell. When you find unvisited land, that is a new island: count it, then flood fill (DFS or BFS) to mark all of its land as visited so you do not count it again.
Scan from the top-left. Cell (0,0) is unvisited land: island 1. Flood fill from here.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Every cell is visited a constant number of times, so this is O(rows × cols). Try BFS on a grid yourself with the shortest-path exercise:
Shortest path in a grid
You get a grid of "." (open) and "#" (wall) cells. Starting at the top-left corner, you can step up, down, left or right onto open cells.
Return the fewest steps to reach the bottom-right corner, or -1 if it cannot be reached (including when either corner is a wall).
[".", ".", "."],
["#", "#", "."],
[".", ".", "."] → 4The grid is a list of rows; each row is a list of one-character strings. A 1x1 open grid needs 0 steps.
Topological sort: ordering with dependencies
You have courses where some require others first. Is there a valid order to take them all? That is a topological sort of a directed graph: an ordering where every edge points forward. It exists exactly when the graph has no cycle.
Kahn's algorithm works by peeling off nodes with no remaining prerequisites. The in-degree of a node is the number of edges pointing into it.
- Count the in-degree of every node.
- Queue every node with in-degree 0 (nothing required).
- Pop a node, add it to the order, and decrease the in-degree of each node it points to. Any that hit 0 join the queue.
- If the order contains every node, you are done. If not, the leftovers are stuck in a cycle.
In-degrees: py needs nothing, algo needs two courses. Queue [py].
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Three courses: 1 needs 0, 2 needs 1, and 0 needs 2. Using topo_order above, what is printed?
print(topo_order(3, [[1, 0], [2, 1], [0, 2]]))
Weighted graphs: Dijkstra in one idea
BFS counts edges. When edges have different weights (minutes of driving, milliseconds of latency), the fewest edges is not the cheapest route. Dijkstra's algorithm fixes this by swapping BFS's queue for a min-heap keyed by total distance so far. Always expand the closest unfinished node next; once a node is popped, its distance is final. That only works when all weights are non-negative.
import heapq
def dijkstra(graph, start): # graph[u] = [(v, weight), ...]
dist = {start: 0}
heap = [(0, start)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry, already found shorter
for v, w in graph[u]:
if d + w < dist.get(v, float("inf")):
dist[v] = d + w
heapq.heappush(heap, (d + w, v))
return distIt runs in O((V + E) log V). That is the network-delay-time practice problem.
Union-find, briefly
Union-find (disjoint set union) tracks which items are in the same group as edges arrive one by one. find(x) returns a group's representative and union(a, b) merges two groups. With path compression (point nodes straight at the root as you search), each operation is effectively constant time. Use it for "count connected components" or "does adding this edge create a cycle?" when edges come as a list.
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False # already connected: this edge makes a cycle
parent[ra] = rb
return TrueMatch the problem to the tool.
Common mistakes:
- Forgetting the visited set and looping forever on a cycle.
- Marking visited when you pop in BFS instead of when you push, so the same node is queued many times.
- Only adding one direction for an undirected edge.
- Using
list.pop(0)(O(n)) as a queue in Python instead ofcollections.deque. - Starting the search from only one node when the graph may have several disconnected pieces.
Number of Islands
You get a map as a grid of strings: "1" is land and "0" is water. Land cells that touch up, down, left or right belong to the same island (diagonals do not count). Return how many islands there are.
[["1","1","0","0"],
["1","0","0","1"],
["0","0","1","1"]] → 2
[["1","0"],
["0","1"]] → 2 (diagonal cells are separate)Constraints
0 <= grid.length <= 300and every row has the same length, at most 300grid[i][j]is"0"or"1"- You may change the grid while you work.
Course Schedule
There are num_courses courses labelled 0 to num_courses - 1. Each pair [a, b] in prerequisites means you must finish course b before course a. Return true if you can finish every course, and false if the requirements make that impossible.
num_courses = 2, prerequisites = [[1, 0]] → true
num_courses = 2, prerequisites = [[1, 0], [0, 1]] → false (each needs the other)
num_courses = 3, prerequisites = [] → trueConstraints
1 <= num_courses <= 20000 <= prerequisites.length <= 50000 <= a, b < num_courses
- adjacency list
- A map from each vertex to its neighbours. O(V + E) memory, the default way to store a graph.
- BFS
- Explore by distance using a queue. Finds shortest paths in unweighted graphs. O(V + E).
- DFS
- Follow a path as deep as possible, then back up. Good for reachability, components and cycles.
- topological sort
- An order where every directed edge points forward. Exists only for a DAG. Kahn's algorithm peels off in-degree 0 nodes.
- Dijkstra
- Shortest paths with non-negative weights: BFS with a min-heap keyed by distance so far.
- union-find
- Tracks groups under merges with near O(1)
findandunion. Detects cycles in undirected edge lists.