Back to the 2024 paper

Module 3: Graph and Tree Algorithms

20247m

Answer the following:
(i) Compare and contrast the BFS and DFS traversal techniques in terms of their algorithmic approach, time complexity, data structures used, and typical applications.
(ii) Give examples where one is preferred over the other.

Worked SolutionAI Assisted

BFS vs DFS — Algorithmic Comparison

Aspect BFS (Breadth-First) DFS (Depth-First)
Strategy Level-order using queue; explores all neighbors of current level before going deeper. Depth-first using stack (recursion); goes as deep as possible, backtracks.
Algorithm queue Q={s}; visited[s]; while Q not empty: v=dequeue; for each w adj to v if not visited: visit, enqueue DFS(v): visited[v]=true; for each w adj to v if not visited: DFS(w) (or iterative stack)
Time O(V+E)O(V+E) with adjacency list, O(V2)O(V^2) with matrix. O(V+E)O(V+E) / O(V2)O(V^2) same.
Space O(V)O(V) queue + visited; worst O(V)O(V) (broad level) — more memory for wide graphs. O(V)O(V) stack/recursion, worst O(V)O(V) depth; often less memory for deep narrow graphs, but recursion may overflow.
Tree vs Stack Finds shortest path (fewest edges) in unweighted graph; level = distance from source. Finds any path, not shortest; useful for connectivity, cycles, topological sort, strongly connected components.
Traversal Order Visiting order by distance layers: s, all distance1, then distance2... (example linear). Visiting order by depth: s→first neighbor→its neighbor... deeper first, pre-order.
Applications Shortest path unweighted, peer-to-peer, web crawling breadth, social network 1st-degree, bipartite check, Ford-Fulkerson (Edmonds-Karp uses BFS). Topological sort, cycle detection, articulation points, Kosaraju SCC, maze solving, backtracking, solving puzzles.
Completeness Complete on infinite graphs with finite branching (if solution at finite depth). Not complete on infinite depth without visited set.

Example on graph A→B,C etc: BFS from A order: A, B,C, D,E (level1,2) vs DFS order: A,B,D,E,C etc depending on adjacency order.

Hybrid: Iterative deepening DFS combines BFS completeness with DFS memory.

Similar questions

AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.