""" search.py an example of recursive depth first search The graph is the one at https://cs.bennington.college/courses/spring2022/algorithms/misc/a_graph.png $ python search.py Visiting node a Visiting node b Visiting node e Visiting node f Visiting node c Visiting node g Visiting node h Visiting node d Jim Mahoney | cs.bennington.college | April 7 2022 | MIT License """ # Save some typing. a='a'; b='b'; c='c'; d='d'; e='e'; f='f'; g='g'; h='h' # Graph description as an "adjacency list". # The keys are the nodes; the values are neighbors. graph = { a: [b, c, d], b: [a, e, f], c: [a, f, g, h], d: [a, h], e: [b], f: [b, c, h], g: [f], h: [c, d] } def search(graph, node, visited={}): """ depth-first recursive search """ visited[node] = True print("Visiting node ", node) for neighbor in graph[node]: if not neighbor in visited: search(graph, neighbor, visited) search(graph, a)