Your question is BFS or DFS Traversal. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
Gartner Peer Insights models related products and categories as a graph. Given an adjacency-list representation, a starting node, and a traversal method, return the nodes reachable from the start in traversal order.
Implement both methods:
When multiple neighbors are available, process them in the order listed in the adjacency list. For iterative DFS, add neighbors to the stack in reverse order so the first listed neighbor is visited first. Each node must appear at most once, even when cycles or multiple paths exist.
Implement graph_traversal(graph, start, method), where graph is a dictionary mapping node names to lists of neighboring node names, start is a node in the graph, and method is either "bfs" or "dfs". Return a list of node names in the requested traversal order.
def graph_traversal(graph, start, method):