Graphs: BFS/DFS
Read a little, play a little. No scary maths, and no rush.
Maps, friends, and islands
A graph is just things plus connections: cities and roads, people and friendships, grid cells touching edge-to-edge. Trees (from the last chapter) are graphs with no cycles — so everything you learned about BFS and DFS transfers directly. The only new skill is remembering where you've been, because graphs loop back on themselves.
Number of islands: the canonical first graph problem
Count blobs of 1s in a sea of 0s. Strategy: scan every cell; when you find land, flood-fill the whole island (flipping it to water as you go) and add one to the count. Each island gets "sunk" exactly once:
def islands(g):
R, C = len(g), len(g[0])
count = 0
def dfs(r, c):
if not (0 <= r < R and 0 <= c < C) or g[r][c] != '1':
return
g[r][c] = '0' # sink it so we never recount
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
dfs(r + dr, c + dc)
for r in range(R):
for c in range(C):
if g[r][c] == '1':
dfs(r, c)
count += 1
return count
Mutating the grid doubles as the visited set — a beloved interview shortcut (mention you'd use a separate set if mutation weren't allowed).
BFS vs DFS: which explorer?
- DFS (stack/recursion): dives deep first. Natural for "explore everything connected" — islands, path existence, clone graph.
- BFS (queue, level by level): first arrival is the shortest path in unweighted graphs. Rotting oranges, shortest word ladder, social degrees.
Same visited discipline either way; only the container changes.
Representing a graph
Problems usually give a list of edges, such as [[A, B], [A, C], [B, D]]. Turn it into an adjacency list first: a dictionary from each node to its neighbors. It is compact and lets you visit a node's neighbors directly. An adjacency matrix (a grid of yes/no) suits small, dense graphs. Either way, BFS and DFS visit each node and each edge once, so they run in O(V + E): vertices plus edges.
BFS shortest path, traced
Edges: A–B, A–C, B–D, C–D, D–E. Shortest number of steps from A to E:
- Level 0: A.
- Level 1: B and C, both one step away.
- Level 2: D, reached from B first. When C tries D, it is already visited.
- Level 3: E.
E is 3 steps away. BFS guarantees this is the minimum, because every node at distance 2 was processed before any node at distance 3.
Mark visited when you enqueue
Mark a node as visited the moment you add it to the queue, not when you take it out. Otherwise the same node can be queued many times by different neighbors before it is processed, wasting time and sometimes producing wrong counts.
Directed graphs and ordering
When edges have a direction, such as "course A must come before course B," a common question is whether a valid order exists. Topological sort answers it: repeatedly take a node with no remaining prerequisites, remove its outgoing edges, and continue. If you get stuck while nodes remain, there is a cycle, and no valid order exists.
Grids are graphs too
A grid problem is a graph in disguise: each cell is a node, and its up, down, left, and right neighbors are its edges. That is why number of islands, flood fill, and shortest path through a maze all use these same two walks.
Remember this
- Graphs = trees + cycles; visited-tracking is the whole ballgame.
- Flood-fill for blobs, BFS levels for shortest steps.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue