Skip to content

Instantly share code, notes, and snippets.

@IevaZarina
Created November 7, 2016 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IevaZarina/f2a6c3b971775b6ec1107cae4add8662 to your computer and use it in GitHub Desktop.
Save IevaZarina/f2a6c3b971775b6ec1107cae4add8662 to your computer and use it in GitHub Desktop.
Simple depth-first searcher in Python 2.7
'''
Depth-first searcher
Tree:
a
/ \
b c
/|\ \
d e f g
|
h
'''
tree = {
'a': ['b', 'c'],
'b': ['d', 'e', 'f'],
'c': ['g'],
'g': ['h'],
}
# Depth first search with stack
def dfs(tree, target, start):
stack = [start]
visited = set()
while stack:
if stack[-1] == target:
return target
visited.add(stack[-1])
children = tree[stack[-1]] if stack[-1] in tree else []
new_child = None
for child in children:
if child not in visited:
new_child = child
break
if new_child:
stack.append(new_child)
else:
stack.pop(-1)
return None
start = 'a'
test_set = ['a', 'b', 'c', 'f', 'g', 's']
for t in test_set:
print "DFS searching", t, ':', dfs(tree, t, start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment