Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def depth_first_search(start, goal, graph):
- """
- start is a str representation of a node in the graph
- goal is a str representation of a node in the graph
- graph is a dictionary of adjacency lists
- e.g. graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['B', 'C']}
- """
- explored = set()
- stack = [[start]]
- viable_paths = []
- if start == goal:
- viable_paths.append([start])
- while stack:
- path = stack.pop()
- node = path[-1]
- if node not in explored:
- for neighbor in graph[node]:
- new_path = path[:]
- new_path.append(neighbor)
- if neighbor == goal:
- viable_paths.append(new_path)
- else:
- stack.append(new_path)
- return viable_paths
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement