ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (depth-first traversal of a graph given as an adjacency list)?

What will be the output of the following pseudocode (depth-first traversal of a graph given as an adjacency list)?
Map graph = {0: [1, 2], 1: [3], 2: [3], 3: []}
List visited = empty list
Function dfs(Integer u)
    if (u in visited)
        return
    end if
    append(visited, u)
    for (each v in graph[u])
        dfs(v)
    end for
End Function

dfs(0)
Print visited
  1. A. [0, 1, 2, 3]
  2. B. [0, 1, 3, 2]
  3. C. [0, 2, 3, 1]
  4. D. [0, 2, 1, 3]

Correct answer: B. [0, 1, 3, 2]

DFS visits 0, then recurses into its first neighbor 1, then 1's neighbor 3 (marking it visited), then backtracks to 0's second neighbor 2 -- but 3 is already visited, so dfs(2) just adds 2 itself (its call to dfs(3) returns immediately). Order: [0, 1, 3, 2].

More Pseudocode and Code Tracing questions

Exams that ask this topic