Recursion

Graph BFS

Lesson
Graph BFS - image

Just like with Tree BFS, we can get Graph BFS code by simply taking the preorder Iterative Tree DFS code, and swapping out the stack with a queue. And now that we're on a Graph, we need to keep track of the nodes we've visited so we don't enter an infinite cycle.

# A queue of all the nodes we want to call visitAll() on.
queue = deque([root])
visited_nodes = set() 
while queue:

    # take a node off the queue and visit it
    node = queue.popleft() 

    if node in visited_nodes: 
        continue
    visited_nodes.add(node)

    do_something(node) 

    for nbr in node.neighbors:
        queue.append(nbr)
Mark as Completed:
Submits:
test
Test your code to get an output here!