Consider the following sequences of nodes for the undirected graph shown…

2008

Consider the following sequences of nodes for the undirected graph shown below:

image.png
  1. a b e f d g c

  2. a b e f c g d

  3. a d g e b c f

  4. a d b c g e f

A Depth First Search (DFS) is started at node a. The nodes are listed in the order they are first visited. Which of the above can be produced as DFS outputs?

Answer: B. 2 and 3 onlyCONCEPTA DFS preorder is controlled by the recursion stack. From the vertex at the top of the stack, DFS must visit an unvisited adjacent vertex whenever one…

  1. A.

    1 and 3 only

  2. B.

    2 and 3 only

  3. C.

    2, 3 and 4 only

  4. D.

    1, 2, and 3

Attempted by 187 students.

Show answer & explanation

Correct answer: B

CONCEPT

A DFS preorder is controlled by the recursion stack. From the vertex at the top of the stack, DFS must visit an unvisited adjacent vertex whenever one exists; it may pop that vertex only after all of its neighbors have already been visited.

Therefore, for a proposed preorder, each next vertex must be reachable from the current stack top after popping only vertices that have no unvisited neighbors left.

APPLICATION

  1. Sequence 1: after a → b → e → f, the stack top is f. Vertices c and g are still unvisited neighbors of f, so f cannot be popped to reach d next. This sequence violates the DFS stack rule.

  2. Sequence 2: follow a → b → e → f → c. After c has no unvisited neighbor, return to f, continue to g, and then visit d from g. This realizes a → b → e → f → c → g → d.

  3. Sequence 3: choose successive unvisited neighbors a → d → g → e → b → c → f. Every next vertex is available from the current stack top, so this preorder is realizable.

  4. Sequence 4: after a → d → b → c, the stack top is c. Vertices e and f are still unvisited neighbors of c, so c cannot be popped to reach g next. This sequence violates the DFS stack rule.

CROSS-CHECK

The constructive traces certify sequences 2 and 3. The remaining-neighbor checks at f in sequence 1 and at c in sequence 4 independently show where their proposed preorder would require premature backtracking.

RESULT

Exactly sequences 2 and 3 are possible, so the answer is “2 and 3 only”.

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

Explore the full course: Coding For Placement

Loading lesson…