The Breadth First Search (BFS) algorithm has been implemented using the queue…

2017

The Breadth First Search (BFS) algorithm has been implemented using the queue data structure. Which one of the following is a possible order of visiting the nodes in the graph below?

  1. A.

    \(\text{MNOPQR}\)

  2. B.

    \(\text{NQMPOR}\)

  3. C.

    \(\text{QMNROP}\)

  4. D.

    \(\text{POQNMR}\)

Attempted by 359 students.

Show answer & explanation

Correct answer: D

Key insight: BFS visits nodes level by level using a queue and marks nodes when they are enqueued, so nodes discovered earlier are always visited earlier.

  • Step 1: Start at P. Queue = [P]. Visit P and enqueue its neighbors in some order; assume O then Q. Visited so far: P.

  • Step 2: Dequeue O and visit it. O enqueues its unvisited neighbor N (Q was already enqueued). Visited order: P, O.

  • Step 3: Dequeue Q and visit it. Q enqueues its remaining unvisited neighbor M (N already enqueued). Visited order: P, O, Q.

  • Step 4: Dequeue N and visit it. No new nodes are added. Visited order: P, O, Q, N.

  • Step 5: Dequeue M and visit it; it enqueues R. Visited order: P, O, Q, N, M.

  • Step 6: Dequeue R and visit it. Final BFS order: P O Q N M R.

Conclusion: POQNMR is achievable with BFS (starting at P and with the adjacency ordering shown), so the sequence POQNMR is a valid BFS visitation order. The other sequences are not possible under standard BFS behavior because they require visiting nodes discovered later before earlier-enqueued nodes.

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

Explore the full course: Gate Guidance By Sanchit Sir