Created
November 7, 2016 21:17
-
-
Save IevaZarina/f2a6c3b971775b6ec1107cae4add8662 to your computer and use it in GitHub Desktop.
Simple depth-first searcher in Python 2.7
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
''' | |
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