BFS of Graph
Return the breadth-first traversal order of a graph given as an adjacency list.
Open on GeeksforGeeks ↗Intuition
BFS explores in rings: everything one hop away, then two hops, and so on. A FIFO queue is what enforces that — newly discovered vertices go to the back, behind everything already waiting. Marking a vertex when it is enqueued (not when dequeued) is essential, otherwise a vertex reachable by two edges gets queued twice.
Approach
Queue, not stack
Seed the queue with the start vertex and mark it. Repeatedly pop from the front, record it, and push its unvisited neighbours to the back.
Mark at enqueue time
If you only mark on dequeue, a vertex with two incoming edges enters the queue twice and is reported twice. Marking as it is queued guarantees exactly one visit.
Why the order is layered
Everything at distance k is queued before anything at distance k+1, so BFS also yields shortest hop-counts on an unweighted graph for free.
Solution & live demo
Edge cases
Outer loop starts a new BFS at each unvisited vertex.
Marked at first enqueue, so the second edge finds it already seen.
Queued, popped, recorded — one step.