Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created October 27, 2014 09:51
Show Gist options
  • Save CMCDragonkai/e58ecc3c9871031e91d9 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/e58ecc3c9871031e91d9 to your computer and use it in GitHub Desktop.
Python: Depth First Search on a Adjacency List - returns a list of nodes that can be visited from the root node.
def depth_first_search(neighbour_list, root_node):
visited_nodes = set()
stack = [root_node]
while stack:
node = stack.pop()
if node not in visited_nodes:
visited_nodes.add(node)
stack.extend(set(neighbour_list[node]) - visited_nodes)
return list(visited_nodes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment