Advertisement
Guest User

Depth First Search

a guest
Jan 19th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. def depth_first_search(start, goal, graph):
  2.     """
  3.     start is a str representation of a node in the graph
  4.     goal is a str representation of a node in the graph
  5.     graph is a dictionary of adjacency lists
  6.  
  7.     e.g. graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['B', 'C']}
  8.     """
  9.     explored = set()
  10.     stack = [[start]]
  11.     viable_paths = []
  12.  
  13.     if start == goal:
  14.         viable_paths.append([start])
  15.  
  16.     while stack:
  17.         path = stack.pop()
  18.         node = path[-1]
  19.  
  20.         if node not in explored:
  21.             for neighbor in graph[node]:
  22.                 new_path = path[:]
  23.                 new_path.append(neighbor)
  24.  
  25.                 if neighbor == goal:
  26.                     viable_paths.append(new_path)
  27.                 else:
  28.                     stack.append(new_path)
  29.  
  30.     return viable_paths
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement