Consider the following graph : For the graph; the following sequences of depth…

2022

Consider the following graph :

For the graph; the following sequences of depth first search (DFS) are given
(A) abcghf
(B) abfchg
(C) abfhgc
(D) afghbc

Which of the following is correct ?

  1. A.

    (A),(B) and (D) only 

  2. B.

    (A),(B),(C) and (D)

  3. C.

    (B), (C) and (D) only

  4. D.

    (A),(C) and (D) only 

Attempted by 336 students.

Show answer & explanation

Correct answer: D

Answer: The valid DFS sequences are "abcghf", "abfhgc" and "afghbc". The sequence "abfchg" is not a valid DFS traversal for the given graph.

Key idea:

  • Depth-first search (DFS) explores as far as possible along one branch before backtracking. When you move from a vertex down to a neighbor, you must complete that neighbor's reachable subtree (possibly by backtracking) before visiting nodes that belong to a different branch higher in the stack.

Why the three listed sequences are valid (sketches of how DFS can produce them):

  • "abcghf": Start at a, visit b next, then traverse into the branch that leads to c and from there go deeper to g and h. After finishing that branch, backtrack up and finally visit the remaining neighbor f. This order respects the DFS rule of finishing a subtree before moving to another branch.

  • "abfhgc": Start at a, visit b, then choose to visit f next and go deep into f's reachable subtree (visiting h and g in that order) before backtracking to b and then visiting c. This is a valid DFS ordering obtained by choosing the neighbor order at each step appropriately.

  • "afghbc": Start at a but pick the neighbor f first. Explore f's reachable subtree (for example h then g). After finishing that subtree, backtrack to a and then visit b and subsequently explore the branch containing c. This also follows DFS rules.

Why the sequence "abfchg" is not valid:

  • The sequence "abfchg" would require visiting c after descending from b into f without having completed the subtree reachable from f. That order implies switching to a different branch of b while still in the middle of exploring f's branch, which violates the depth-first rule that a branch must be finished (including any deeper reachable nodes) before exploring a different branch higher in the call stack.

  • Therefore no choice of neighbor-visitation ordering can produce the visitation list "abfchg" while following standard DFS behavior on the given graph.

Summary: The only DFS sequences from the list that obey the DFS property on this graph are "abcghf", "abfhgc" and "afghbc".

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Coding For Placement