Breadth-First Search Order
graph maps each node name to the array of its neighbours, in order. Return the nodes reachable from source in breadth-first order: the source, then its neighbours in the given order, then theirs, each node once.
bfs({ A: ["B", "C"], B: ["D", "E"], C: ["F", "G"], D: [], E: [], F: [], G: [] }, "A") -> ["A", "B", "C", "D", "E", "F", "G"]
bfs({ A: ["B"], B: ["C"], C: ["A"] }, "A") -> ["A", "B", "C"]Hints
Hint 1
Mark a node visited when it is enqueued, not when it is dequeued, or a node reachable two ways is listed twice.
Hint 2
Walk the queue with an index instead of shift(), which is O(n) on long arrays.