Skip to content

Instantly share code, notes, and snippets.

@sergeyprokudin
Created January 10, 2019 18:21
Show Gist options
  • Save sergeyprokudin/f2e9f35a5404899719337670521955eb to your computer and use it in GitHub Desktop.
Save sergeyprokudin/f2e9f35a5404899719337670521955eb to your computer and use it in GitHub Desktop.
Vanilla graph depth first search implementation in Python
def dfs(g, curr_node, visited=None):
"""
Parameters
----------
graph: dictionary
dictionary of nodes and its neighbors
node: list
Returns
-------
visited: set
a set of visited graph nodes
Algo: add current node to the list of visited
"""
if visited is None:
visited = set()
visited.add(curr_node)
print("added %d" % curr_node)
for neigh_node in g[curr_node]:
if neigh_node not in visited:
dfs(g, neigh_node, visited)
return visited
g = {0:[8, 1, 3, 4], 1:[0,2, 5], 2:[1, 3], 3:[4], 4:[0], 5:[1], 8:[0]}
dfs(g, curr_node=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment