Created
January 10, 2019 18:21
-
-
Save sergeyprokudin/f2e9f35a5404899719337670521955eb to your computer and use it in GitHub Desktop.
Vanilla graph depth first search implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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