Many graph algorithms start by visiting every vertex reachable from a source in a systematic way. The two standard traversals are breadth-first search, which explores in layers, and depth-first search, which goes as deep as possible before backing up.
Breadth-first search (BFS)
Mark the source visited and put it in a queue.
While the queue is not empty: take out the front vertex u and visit it; for every unvisited neighbour v of u, mark v visited and add it to the queue.
Because a queue is FIFO, vertices are visited in order of their number of edges from the source; BFS therefore finds shortest paths in an unweighted graph.
Depth-first search (DFS)
DFS with discovery and finishing times
DFS(G): for each vertex u: if u is not visited: DFS-VISIT(u)DFS-VISIT(u): mark u visited; time = time + 1; d[u] = time /* discovered */ for each neighbour v of u: if v is not visited: DFS-VISIT(v) time = time + 1; f[u] = time /* finished */
DFS is naturally recursive (or uses an explicit stack, Unit 4). The discovery time d[u] is when u is first reached; the finishing time f[u] is when all its descendants are done. If the search from the first source does not reach every vertex, DFS restarts from an unvisited vertex, producing a DFS forest.
BFS: queue, level by level, shortest paths in unweighted graphs.
DFS: recursion/stack, deep first, discovery time d and finishing time f.
Different neighbour orders give different (equally valid) traversal orders.
Both are O(n+e) with lists, O(n2) with a matrix.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Perform BFS and DFS on the undirected graph with edges 1–2, 1–3, 2–4, 3–4, 4–5, starting at 1 and taking neighbours in increasing order. Give the DFS discovery/finishing times.
Show worked answer
BFS: queue 1 → visit 1, queue 2, 3 → visit 2, queue 4 → visit 3 (4 already queued) → visit 4, queue 5 → visit 5. BFS order: 1 2 3 4 5. DFS: 1 (d = 1) → 2 (d = 2) → 4 (d = 3) → 3 (d = 4; its neighbours 1 and 4 are visited) finishes f = 5 → back at 4, go to 5 (d = 6), f = 7 → 4 finishes f = 8 → 2 finishes f = 9 → 1 finishes f = 10. DFS order: 1 2 4 3 5; times 1: 1/10, 2: 2/9, 4: 3/8, 3: 4/5, 5: 6/7.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-208/graphs/breadth-first-and-depth-first-search/ to read this page.