Skip to content

Lesson 19 of 40Trees and graphs

Graphs

Model problems as nodes and edges, then explore them with BFS, DFS, topological sort and Dijkstra.

22 min read0/4 questions

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 listAdjacency matrix
Shape{ "A": ["B", "C"], ... }V × V grid of 0/1 (or weights)
MemoryO(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 whenAlmost 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 directions
Quick check
A social network has 2 billion users, each with about 300 friends. Why does nobody store it as an adjacency matrix?
Need a nudge? A hint rules out a wrong answer.

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.

BFS from A
A0BCDE

currentwaitingdone

Start at A, distance 0. Mark it visited when it enters the queue.

1/5
Python
from collections import deque graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]} def bfs_distances(graph, start): dist = {start: 0} # doubles as the visited set queue = deque([start]) while queue: node = queue.popleft() for nxt in graph[node]: if nxt not in dist: dist[nxt] = dist[node] + 1 queue.append(nxt) return dist print(bfs_distances(graph, "A"))
Output
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.

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?".

DFS from A
A1BCDE

currentwaitingdone

Visit A (order 1). Go to its first unvisited neighbour, B.

1/5
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.

Quick check
In an unweighted maze, you need the fewest moves from start to exit. Which search?
Need a nudge? A hint rules out a wrong answer.

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.

Counting islands with flood fill
11000
11001
00101
00011

Scan from the top-left. Cell (0,0) is unvisited land: island 1. Flood fill from here.

1/4
Python
def num_islands(grid): rows, cols = len(grid), len(grid[0]) seen = set() def fill(r, c): if not (0 <= r < rows and 0 <= c < cols): return if grid[r][c] != "1" or (r, c) in seen: return seen.add((r, c)) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): fill(r + dr, c + dc) count = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1" and (r, c) not in seen: count += 1 fill(r, c) return count grid = [list("11000"), list("11001"), list("00101"), list("00011")]print(num_islands(grid))
Output
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:

ChallengeMedium

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).

[".", ".", "."],
["#", "#", "."],
[".", ".", "."]      →  4

The grid is a list of rows; each row is a list of one-character strings. A 1x1 open grid needs 0 steps.

def shortest_path(grid: list[list[str]]) -> int: # Breadth-first search from (0, 0). Track distance per cell. pass

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.

  1. Count the in-degree of every node.
  2. Queue every node with in-degree 0 (nothing required).
  3. 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.
  4. If the order contains every node, you are done. If not, the leftovers are stuck in a cycle.
Kahn's algorithm (labels are in-degrees)
py0ds1web1algo2

currentwaitingdone

In-degrees: py needs nothing, algo needs two courses. Queue [py].

1/4
Python
from collections import deque def topo_order(n, prereqs): graph = [[] for _ in range(n)] indegree = [0] * n for course, before in prereqs: # "before" must come first graph[before].append(course) indegree[course] += 1 queue = deque(i for i in range(n) if indegree[i] == 0) order = [] while queue: node = queue.popleft() order.append(node) for nxt in graph[node]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return order if len(order) == n else [] # [] means a cycle print(topo_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]]))print(topo_order(2, [[0, 1], [1, 0]]))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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]]))
Need a nudge? Hints walk you through it.

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 dist

It 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 True
Match the pairs0/5 matched

Match the problem to the tool.

Choose an item, then its match on the other side.

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 of collections.deque.
  • Starting the search from only one node when the graph may have several disconnected pieces.
ChallengeMedium

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 <= 300 and every row has the same length, at most 300
  • grid[i][j] is "0" or "1"
  • You may change the grid while you work.
def num_islands(grid: list[list[str]]) -> int: # Scan every cell. When you land on a 1, flood the whole island. pass
ChallengeMedium

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 = []                →  true

Constraints

  • 1 <= num_courses <= 2000
  • 0 <= prerequisites.length <= 5000
  • 0 <= a, b < num_courses
def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool: # Build a graph and check whether it has a cycle. pass
Key terms
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) find and union. Detects cycles in undirected edge lists.
Interview pattern: Graphs33 problemsSpot it: Grids · networks · dependencies · shortest path · islands