The Breadth First Search algorithm has been implemented using the queue data…

2008

The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting the nodes of the following graph is

image.png

  1. A.

    MNOPQR

  2. B.

    NQMPOR

  3. C.

    QMNPRO

  4. D.

    QMNPOR

Attempted by 293 students.

Show answer & explanation

Correct answer: C

Solution summary: The sequence Q M N P R O is a valid BFS order when starting at node Q (assuming Q's neighbors are visited in the order M, N, P).

  1. Start at Q: mark Q visited and enqueue it. Queue = [Q]. Visit order so far: Q.

  2. Dequeue Q and discover its neighbors in the order M, N, P. Enqueue M, N, P. Queue = [M, N, P]. (Nodes M, N, P are now discovered.)

  3. Dequeue M and visit it. M's undiscovered neighbor R is enqueued. Queue = [N, P, R]. Visit order: Q, M.

  4. Dequeue N and visit it. N's undiscovered neighbor O is enqueued. Queue = [P, R, O]. Visit order: Q, M, N.

  5. Dequeue P and visit it. P has no new neighbors to enqueue (O is already enqueued). Queue = [R, O]. Visit order: Q, M, N, P.

  6. Dequeue R and visit it. Queue = [O]. Visit order: Q, M, N, P, R.

  7. Dequeue O and visit it. Queue = []. Final visit order: Q, M, N, P, R, O.

Conclusion: The BFS traversal order Q M N P R O matches the steps above, so the option showing Q M N P R O is correct.

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

Explore the full course: Gate Guidance By Sanchit Sir