Introduction
Most graph questions begin with the same step: visit every vertex that can be reached from a starting point. Which towns can a bus reach? Is the network still connected after a cable fails? What is the fewest number of clicks from one page to another? Two search methods answer these questions, breadth-first search (BFS) and depth-first search (DFS). They differ only in the order in which they pick the next vertex, and both run in time proportional to the size of the graph.
How it works
A graph is stored as an adjacency list: for each vertex, the list of its neighbours. In Python, a dictionary of lists does the job: graph[v] is the list of vertices adjacent to v. For an undirected graph, each edge is stored twice, once for each end.
Breadth-first search explores in rings. It visits the start, then all its neighbours, then all their unvisited neighbours, and so on, so vertices are visited in increasing order of their distance from the start. It keeps a queue (first in, first out) of vertices waiting to be explored. The steps:
- Put the start in the queue and mark it visited, with distance 0.
- Take the front vertex v out of the queue.
- For each neighbour w of v that is not marked, mark it, set its distance to the distance of v plus 1, and add it to the queue.
- Repeat from step 2 until the queue is empty.
Because the first time a vertex is reached is along a shortest route, BFS finds the shortest path (fewest edges) from the start to every reachable vertex. To recover a path, remember each vertex's parent, the vertex it was first reached from, and follow parents back from the target.
Depth-first search uses a stack (last in, first out), or recursion, which uses the call stack: from the current vertex it moves to the first unvisited neighbour and only backs up when there is none. DFS suits questions that explore one possibility to the end, such as finding cycles, ordering tasks by their dependencies, solving mazes and checking connectivity.
A connected component is a maximal group of vertices that can all reach each other. To count them, loop over all vertices; whenever one is unvisited, start a new search from it, mark everything it reaches and add 1 to the count.
Both searches handle each vertex once and look at each edge twice (once from each end), so the time is proportional to the number of vertices plus edges. The marking is essential: without it, a cycle would send the search round and round for ever.
Example
from collections import deque
graph = {
1: [2, 3],
2: [1, 4],
3: [1, 4, 5],
4: [2, 3],
5: [3],
6: [7],
7: [6],
}
def bfs(start):
dist = {start: 0}
queue = deque([start])
order = []
while queue:
v = queue.popleft()
order.append(v)
for w in graph[v]:
if w not in dist:
dist[w] = dist[v] + 1
queue.append(w)
return order, dist
order, dist = bfs(1)
print("visit order:", order)
print("distances:", dist)
print("not reached:", [v for v in graph if v not in dist])Line by line
graphis an adjacency list for seven vertices. Vertices 6 and 7 are joined to each other but not to the rest.distdoubles as the "visited" mark: a vertex is indistonce it has been found.- The
whileloop takes the front vertex from the queue, appends it toorderand examines its neighbours; each new one gets its distance and joins the queue. - Starting from 1, the search visits 2 and 3 (distance 1), then 4 and 5 (distance 2). Vertices 6 and 7 are never reached, and the last line lists them.
Expected result
visit order: [1, 2, 3, 4, 5]
distances: {1: 0, 2: 1, 3: 1, 4: 2, 5: 2}
not reached: [6, 7]
In the real world
Search engines crawl the web with a BFS-like method, and social networks use it to show "people you may know" at distance two. Route planners start from BFS on unweighted maps, and games use it to find the shortest way across a grid. Network tools find which machines are still reachable after a failure, image editing programs fill a region with DFS ("flood fill"), and build systems order tasks by the dependencies found with DFS.
Common mistakes
- Not marking vertices as visited. The search runs for ever on a cycle, or visits the same vertex many times.
- Marking a vertex when taking it out of the queue instead of when adding it. The same vertex can then enter the queue twice.
- Using a list as a queue with
pop(0). It is slow for big graphs; usecollections.deque. - Using BFS distances on a graph with edge weights. BFS counts edges, not total length.
- Forgetting that a graph may be disconnected. One search from one vertex finds only one component.
Best practices
- Build the adjacency list once, then search it many times.
- Visit neighbours in a fixed order, such as increasing, if you need repeatable output.
- Keep the parent of each vertex when you need the path itself, not only the distance.
- Choose BFS for shortest paths in unweighted graphs and DFS for exhaustive exploration.
Summary
A graph is stored as an adjacency list, and a search marks each vertex the first time it is found. BFS uses a queue, visits vertices by increasing distance and gives shortest paths when every edge counts as one step; DFS uses a stack or recursion and goes deep before backing up. Starting a new search from each unvisited vertex counts the connected components.
Quick check
Key takeaways
- Mark each vertex as visited the first time you see it, so every vertex and edge is handled once.
- A queue gives breadth-first order and a stack gives depth-first order.
- BFS finds the fewest-edge distance from the start to every reachable vertex.
- The number of connected components is the number of times a new search must be started.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.