AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumgraphdfs

~120s

Depth-first visiting order

An undirected graph has these adjacency lists:

VertexAdjacent vertices
AB, C
BA, D
CA, E
DB, E
EC, D, F
FE

A depth-first search starts at A and always moves to the unvisited neighbour that comes first alphabetically. In what order are the vertices visited?

Show the answer and the worked solution

Correct answer: B.

A, B, D, E, C, F

Worked solution

  1. From A the alphabetically first neighbour is B, so B is visited.
  2. B's neighbours are A (visited) and D, so D is visited.
  3. D's neighbours are B (visited) and E, so E is visited.
  4. E's unvisited neighbours are C and F, and C comes first; C is visited, and both of C's neighbours are already visited.
  5. Backtracking to E leaves F, which is visited last, giving A, B, D, E, C, F.

Answer: A, B, D, E, C, F.

The idea

A DFS order is fixed only once the tie-breaking rule is fixed. Backtracking is the step candidates forget: the walk resumes at the deepest vertex that still has an unvisited neighbour.

Shortcut. A → B → D → E is forced; at E the alphabetical rule picks C before F, and C is a dead end, so F comes last.

Common trap. "A, B, C, D, E, F" is the breadth-first order, visiting A's neighbours B and C before going deeper.

Depth-first visiting order — Aptitude Question

Depth-first visiting order: An undirected graph has these adjacency lists: | Vertex | Adjacent vertices |… Answer and worked solution on CodeKairo.

Question

An undirected graph has these adjacency lists:

VertexAdjacent vertices
AB, C
BA, D
CA, E
DB, E
EC, D, F
FE

A depth-first search starts at A and always moves to the unvisited neighbour that comes first alphabetically. In what order are the vertices visited?

Options

  1. A, B, C, D, E, F
  2. A, B, D, E, C, F
  3. A, B, D, E, F, C
  4. A, C, E, D, B, F
Show the answer and the worked solution

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

Worked solution

  1. From A the alphabetically first neighbour is B, so B is visited.
  2. B's neighbours are A (visited) and D, so D is visited.
  3. D's neighbours are B (visited) and E, so E is visited.
  4. E's unvisited neighbours are C and F, and C comes first; C is visited, and both of C's neighbours are already visited.
  5. Backtracking to E leaves F, which is visited last, giving A, B, D, E, C, F.

Answer: A, B, D, E, C, F.

The idea

A DFS order is fixed only once the tie-breaking rule is fixed. Backtracking is the step candidates forget: the walk resumes at the deepest vertex that still has an unvisited neighbour.

Shortcut. A → B → D → E is forced; at E the alphabetical rule picks C before F, and C is a dead end, so F comes last.

Common trap. "A, B, C, D, E, F" is the breadth-first order, visiting A's neighbours B and C before going deeper.

All Data Structures & Algorithms questions · placement mock tests