Data Structures & AlgorithmsHardGATE CS

An undirected graph has edges A–D, A–F, A–G, B–C, B–F, C–D, C–E, E–G, F–G. An ITERATIVE DFS starts with stack [A]; it pops a vertex, skips it if already visited, otherwise marks and outputs it and pushes all its unvisited neighbours in alphabetical order. What is the output order?

  1. A. A D C B F G E
  2. B. A D F G C B E
  3. C. A G F B C E D
  4. D. A G E C B F D

Correct answer: C. A G F B C E D

Pushing neighbours in alphabetical order means the alphabetically LAST one is popped first, so this stack DFS is not the same as recursive DFS with alphabetical scanning. Simulating the stack gives A G F B C E D.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic