AlgoFrames

BFS order

Warm-up · Trace the algorithm · about 5 min

Run BFS from node 0 on this graph. A node adds its unseen neighbors to the queue in increasing number order.

First predict which node leaves the queue after node 0, then put all nodes in the order BFS takes them from the queue.

Example 1

Input:

{"n":7,"edges":[[0,2],[0,4],[2,1],[2,5],[4,5],[4,3],[5,6]],"directed":false,"source":0}

Output:

[0,2,4,1,5,3,6]

Order of removal from the queue.

Constraints

  • The trace uses the graph shown

Learn the idea first: Breadth-first search, a visual lesson.

More Breadth-first search problems