ProgrammingHardGATE CS & IT · Infosys

What is printed?

What is printed?
def dfs(g, s):
    seen, out, st = set(), [], [s]
    while st:
        u = st.pop()
        if u in seen:
            continue
        seen.add(u)
        out.append(u)
        for v in reversed(g[u]):
            st.append(v)
    return out
g = {1: [2, 3], 2: [4], 3: [4], 4: []}
print(dfs(g, 1))
  1. A. [1, 3, 4, 2]
  2. B. [1, 2, 4, 3]
  3. C. [1, 2, 3, 4]
  4. D. [1, 3, 2, 4]

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

Pushing neighbours in reverse order makes the stack pop 2 first. Node 4 is reached through 2 before 3 is visited, so the order is 1, 2, 4, 3.

More Python Programming questions

Exams that ask this topic