Skip to study material
← Question index

QUESTION 22

Compare DFS and BFS with the same graph.

5 marks

Answer in brief

DFS and BFS both explore reachable vertices, but their pending-work order differs.

Shared requirements

Both need a graph representation, a starting rule and visited tracking. Both must restart at unvisited vertices if the task requires every component. State neighbour order when giving one exact printed sequence.

DFS

It follows a branch before backtracking. On the common five-vertex example with ascending neighbours, it gives 0, 1, 3, 2, 4. An explicit stack or recursion keeps unfinished work. The maximum active depth can reach V.

BFS

It explores level by level using a queue. The same example gives 0, 1, 2, 3, 4. Mark on enqueue to avoid duplicate pending entries. It naturally supports unweighted edge-distance calculations when distances are recorded.

Complexity

Both have O(V + E) time with standard adjacency lists and O(V²) with a matrix full traversal. Both can need O(V) auxiliary storage, although their practical pending-work patterns differ. The choice does not automatically reduce the representation’s own storage.

Choosing

Use BFS for level-order reachability or shortest numbers of unweighted edges. DFS is useful for deep exploration and as a base for analyses that require entering and finishing vertices. Neither basic traversal performs all possible graph applications without additional state or rules.

Reference table

↔ Scroll horizontally on a small screen
Traversal comparison
FeatureDFSBFS
Pending workStack/callsQueue
ExplorationDepth firstLevel first
List timeO(V + E)O(V + E)
Matrix timeO(V²)O(V²)
Auxiliary spaceO(V) worst caseO(V) worst case

Diagram or flowchart

CodeBhavya illustration of graph
Compare DFS and BFS with the same graph. · Download diagram

Related exam questions

The following are topic matches from the supplied papers. Marks are their printed allocations, separate from the practice answer badge.

  • April/May 2023 · Q8 · 10 marks

    Compare BFS and DFS for a graph.

    Paper DS01 · page 2
  • August/September 2022 · Q7(b) · 7 marks

    Compare BFS and DFS with examples.

    Paper DS02 · page 1
  • October 2020 · Q4(a) · 7 marks

    Differentiate BFS and DFS.

    Paper DS06 · page 1

View all matching source questions →