Mental model
A graph search answers "what can I reach from here, and how?" It keeps three kinds of nodes:
- undiscovered (white): not seen yet;
- discovered (gray): seen, but its edges have not all been followed;
- done (black): every edge out of it has been examined.
Each step takes one gray node and looks along its edges for white ones. What differs is which gray node goes next:
- Breadth-first search (BFS) takes the one that has waited longest: a FIFO queue. The start node's neighbours are handled before their neighbours, so the search spreads in rings: everything at distance 1, then everything at distance 2, and so on.
- Depth-first search (DFS) takes the one seen most recently: a stack, here the call stack of a recursive function. It follows one path as deep as possible, then backs up to the last node that still has an unexplored edge.
The lab draws the graph on a circle (so no edge passes behind another node), the queue or call stack as a row in front of it, and the visit order below that. Switch between the presets BFS: levels and DFS: deep first: same graph, same start, very different orders.
Both searches are deterministic only if the neighbour order is. Everything in this lesson, the lab and the four implementations takes neighbours in ascending order (adjacency lists are sorted). With another order you get another valid BFS or DFS, so do not compare your hand trace with a library's output unless you know its order.
Breadth-first search
bfs(adj, start):
dist = [-1] * n; dist[start] = 0
queue = [start]
while queue not empty:
u = queue.dequeue() # visit u
for v in adj[u]: # ascending
if dist[v] != -1: continue # already discovered
dist[v] = dist[u] + 1 # discover v
queue.enqueue(v)
Mark on enqueue, not on dequeue. dist[v] doubles as the visited flag and is set the moment v
is discovered. If you only marked nodes when they leave the queue, a node with several discovered
neighbours could be enqueued several times: wasted work, and in dense graphs up to E queue entries
instead of V.
Why the distances are shortest paths. The queue always holds nodes of at most two consecutive
distances, d followed by d + 1, in that order. Nodes therefore leave the queue in nondecreasing
distance, so the first time any node is discovered, it is discovered from a node as close to the
start as possible. That first discovery fixes dist[v], and it is never improved later. This
holds for unweighted graphs (every edge costs 1). With weights you need Dijkstra's algorithm
(module M26), which replaces the queue with a priority queue.
Store parent[v] = u at discovery and you can rebuild a shortest path to any node by following
parents back to the start. The lab's Nodes panel shows that parent column; the green edges are the
BFS tree it defines.
Depth-first search
dfs(u):
visited[u] = true; discovery.append(u) # u turns gray
for v in adj[u]: # ascending
if visited[v]: continue
dfs(v) # tree edge u → v
finish.append(u) # u turns black
DFS produces two orders. Discovery order (preorder) records when a call starts; finish order (postorder) records when it returns, after everything reachable through unvisited nodes has been explored. Finish order is what topological sorting by DFS and many graph algorithms build on.
The interesting moment is an edge u → v to a node that is not white:
v is… |
Directed graph | Undirected graph |
|---|---|---|
| gray (still on the call stack) | back edge: v is an ancestor of u, so v → … → u → v is a cycle |
if v is u's parent, it is the edge just used, not a cycle; otherwise a back edge and a cycle |
| black (finished) | forward or cross edge: no cycle through it | the edge was already explored from v's side |
So a directed graph has a cycle exactly when DFS finds a back edge. The preset Directed DFS: a cycle reaches edge 4 → 1 while 1 is still gray and marks it in red. That is the cycle test behind DFS-based topological sort.
DFS can also be written with an explicit stack. A version that pushes all neighbours at once and marks nodes when popped visits nodes in a valid depth-first preorder, but not necessarily the same order as the recursion, and it does not give finish times. To reproduce the recursion exactly, keep (node, next-neighbour index) pairs on the stack. That is what the tests use as an independent reference.
Cost: O(V + E)
Both searches do two kinds of work:
- Per node: each reachable node is discovered once and visited once (dequeued or entered). That is O(V).
- Per adjacency entry: when a node is visited, its whole adjacency list is scanned once. Over the whole run that is the sum of all list lengths: E for a directed graph, 2E for an undirected one (each edge is listed at both ends).
Total: O(V + E) time. Extra space is O(V) for the visited/distance arrays plus the queue (at most V entries) or the recursion (at most V frames deep). The Adjacency checks metric in the lab counts exactly the second term; on the connected undirected Grid as a graph preset it equals twice the number of edges.
The bound assumes adjacency lists. With an adjacency matrix, scanning a node's neighbours means reading a whole row of V cells, so both searches become O(V²) no matter how few edges there are (see graph representations).
A single call only reaches the start node's component. Nodes 7 and 8 in the BFS: levels preset stay white. To visit every node, loop over all nodes and start a new search from each one still white. Every new start is a new connected component (undirected) and the total is still O(V + E).
Which one when
| Task | Use | Why |
|---|---|---|
| Fewest edges from a source (unweighted) | BFS | rings of equal distance; first discovery is shortest |
| Shortest path on a grid with 4-neighbour moves | BFS | a grid is an unweighted graph |
| Distance to the nearest of several sources | multi-source BFS | enqueue every source at distance 0 |
| Connected components, flood fill, reachability | either | both visit exactly the reachable set |
| Cycle detection in a directed graph | DFS | back edge to a gray node |
| Topological order, strongly connected components | DFS (finish order) or Kahn's algorithm | ordering falls out of finish times |
| Two-colouring (is the graph bipartite?) | BFS or DFS | colour by level parity; a same-colour edge means odd cycle |
| Very deep or long-path graphs | BFS or iterative DFS | recursion depth = longest DFS path |
Grids are graphs
A grid of R × C cells is a graph with a node per cell and an edge between orthogonal neighbours;
you rarely build it explicitly. Number cell (r, c) as r * C + c, and generate neighbours on the
fly with bounds checks (and walls skipped). The Grid as a graph preset is a 3 × 3 grid built that
way: BFS from the corner discovers cells in diagonal waves, and the distance tag of each cell is
r + c, its Manhattan distance.
Language notes
- C#:
Queue<int>for BFS; recursion for DFS. A default thread stack (1 MB on Windows) holds tens of thousands of small frames, not millions; useStack<T>with (node, index) pairs for huge graphs. - Python: use
collections.dequewithpopleft(), neverlist.pop(0), which shifts the whole list and turns BFS quadratic. Recursive DFS hits the default recursion limit (1,000) on long paths;sys.setrecursionlimitonly moves the problem, so prefer an explicit stack there. - Java:
ArrayDeque<Integer>as the queue (add/remove); avoid the legacyStackclass. Deep recursion throwsStackOverflowError; the thread stack size can be raised, but an iterative version is more robust. - C++:
std::queue<int>(a deque underneath). The visited flags usestd::vector<bool>, a space-optimised bitset specialisation: compact, but its elements are proxies rather than realbool&references.
The teaching implementation
Adjacency builds sorted lists from an edge list; Bfs returns the visit order and distances
(−1 for unreachable); Dfs returns discovery and finish orders. The four languages share the same
structure line by line. Each is tested against one shared fixture of exact orders (directed and
undirected graphs, cycles, unreachable nodes, a grid, a single node, edges given in scrambled order)
and against 500 random graphs: BFS distances are compared with a simple Bellman–Ford relaxation, and
DFS orders with an explicit-stack DFS.
Common mistakes
- Marking visited on dequeue in BFS: duplicates in the queue, and in some variants wrong distances.
- Forgetting the visited check in DFS on a graph with cycles: infinite recursion.
- Treating the parent edge as a cycle in an undirected graph.
- Using BFS distances on weighted graphs. BFS minimises the number of edges, not their total weight.
- Assuming one call visits everything. It reaches one component; loop over all start nodes for the whole graph.
- Relying on an unspecified neighbour order in tests or explanations.
Edge cases
- Start node with no edges: BFS and DFS visit only the start. Try 3 nodes, the single edge
0 1and start node 2. - Directed edges point one way: from a sink, nothing else is reachable even if every other node can reach it (Directed BFS preset).
- Edges
u → vandv → uin a directed graph are two different edges; the lab draws them side by side. In an undirected graph they would be one edge listed twice, which the input rejects. - Self-loops and duplicate edges are rejected by the lab to keep graphs simple; the algorithms themselves would just skip them as already discovered.
Worked practice
1. Undirected graph with edges 0–1, 0–2, 1–3, 2–3, 3–4. Give the BFS order and distances from 0, and the DFS discovery and finish orders.
Answer
Adjacency: 0: 1 2; 1: 0 3; 2: 0 3; 3: 1 2 4; 4: 3. BFS order 0 1 2 3 4 with distances 0, 1, 1, 2, 3. DFS: enter 0, 1, 3, 2 (edge 2–0 is a back edge: cycle 0–1–3–2), finish 2, enter 4, finish 4, 3, 1, 0. Discovery 0 1 3 2 4; finish 2 4 3 1 0.
2. Why can the BFS queue never contain a node at distance d + 2 while a node at distance d is still waiting?
Answer
A node w at distance d + 2 is enqueued while a node x at distance d + 1 is being visited. x itself was discovered from some distance-d node y. By the same argument one level down, every distance-d node was already in the queue before y left it, so all of them were enqueued before x. The queue is FIFO, so by the time x is dequeued (and w enqueued) every distance-d node has left.
3. Directed graph with edges 0 → 1, 1 → 2, 0 → 2. DFS from 0 sees edge 0 → 2 when 2 is already black. Is there a cycle?
Answer
No. 2 was finished during the call on 1, so 0 → 2 is a forward edge. Only an edge to a gray node (still on the stack) proves a cycle.
4. A maze is a 1,000 × 1,000 grid. Which search finds the shortest route from the entrance to the exit, and what does it cost?
Answer
BFS, because every move costs one step. V = 10⁶ cells and E ≤ 2 × 10⁶ edges, so O(V + E) is a few million operations. A recursive DFS would find a route but not necessarily the shortest, and its recursion could reach a million frames deep.
Summary
- BFS uses a FIFO queue and visits nodes in rings of increasing distance; mark nodes when enqueued. Its distances are shortest paths in edges.
- DFS uses recursion (a stack), producing discovery and finish orders; an edge to a gray node is a back edge, and in a directed graph that means a cycle.
- Both run in O(V + E) time with adjacency lists and O(V) extra space; with a matrix they are O(V²).
- One call covers one component; restart from unvisited nodes to cover the graph.
- Fix the neighbour order if you need reproducible traces.