CAP7004 · Unit 6: Graphs
Breadth-first and depth-first search
8 practice questions
Key points
- BFS uses a queue; DFS uses a stack/recursion
- Both O(V+E) with adjacency lists
- BFS gives shortest path in unweighted graphs
- Topological order exists only for DAGs
Both traverse a graph in O(V + E) time with an adjacency list (O(V^2) with a matrix).
BFS explores level by level using a queue. It finds shortest paths in unweighted graphs (fewest edges).
def bfs(g, s):
seen, q, order = {s}, deque([s]), []
while q:
u = q.popleft(); order.append(u)
for v in g[u]:
if v not in seen: seen.add(v); q.append(v)
return order
DFS goes as deep as possible before backtracking, using recursion or an explicit stack.
For the graph A:[B, C], B:[A, D], C:[A, D], D:[B, C, E], E:[D] starting at A:
- BFS order: A B C D E (distances 0 1 1 2 3).
- DFS order: A B D C E.
Uses: BFS for shortest hop count, level-order, web crawling; DFS for cycle detection, topological sort, connected components, path finding, maze solving.
Connected components: run a search from each unvisited vertex; the number of starts is the number of components. For {1:[2], 2:[1], 3:[4], 4:[3], 5:[]} there are 3.
Cycle detection (undirected): a visited neighbour that is not the parent means a cycle.
Topological sort orders a DAG so every edge u -> v has u before v: use Kahn's algorithm (repeatedly remove vertices of in-degree 0) or DFS finish order. Impossible if a cycle exists.
Exam pitfall: mark a vertex visited when it is added to the BFS queue, not when it is removed, or it can be enqueued many times.
Try two questions
The graph {1:[2], 2:[1], 3:[4], 4:[3], 5:[]} has how many connected components?
- 3
- 5
- 1
- 2
Show the answer
A. Component starts: 3 ({1,2}, {3,4}, {5}).
Which graph search finds the path with the fewest edges in an unweighted graph?
- DFS
- Insertion sort
- BFS
- Kruskal
Show the answer
C. BFS reaches vertices in order of distance from the source.