Iteration

We can easily convert our recursive Graph DFS code to iterative code. Usually this isn't necessary, but you should know the basic idea for an interview. Just use your yown custom stack to keep track of calls, instead of relying on the computer's Call Stack.

# A stack of all the nodes we want to call visitAll() on.
stack = [node]

visited_nodes = set() 
while stack:
    # pop from end of stack
    node = stack.pop() 

    # base case
    if node in visited_nodes: 
        continue

    # recursion
    do_something(node) 
    visited_nodes.add(node)
    for nbr in reversed(node.neighbors): # reversed to visit the 0th neighbor first
        stack.append(nbr)
Mark as Completed:
Submits:
test
Test your code to get an output here!