Last active
September 16, 2017 02:12
-
-
Save eloyz/6991865 to your computer and use it in GitHub Desktop.
Depth First Search and Breath First Search Algorithm
http://youtu.be/zLZhSSXAwxI
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(graph, start, result=[]): | |
""" | |
Depth First Search | |
Follow each path in depth until | |
there are no more unvisted nodes. | |
Then reverse until we find an unvisited | |
node and continue to the depth of that path. | |
Repeat until there are no more unvisted nodes. | |
""" | |
stack = [start] | |
while stack: | |
value = stack.pop() | |
if value not in result: | |
result.append(value) | |
stack = stack + graph[value] | |
return result | |
def bfs(graph, start, result=[]): | |
""" | |
Breadth First Search | |
Visit all children nodes then | |
move to next set of unvisted nodes | |
and repeat until there are no more | |
unvisited nodes. | |
""" | |
stack = [start] | |
while stack: | |
value = stack.pop(0) | |
if value not in result: | |
result.append(value) | |
stack = stack + graph[value] | |
return result | |
if __name__ == '__main__': | |
""" | |
Call search algorithms. | |
Print traversal path. | |
""" | |
graph = { | |
'A': ['B', 'D', 'G'], | |
'B': ['A', 'E', 'F'], | |
'C': ['F', 'H'], | |
'D': ['A', 'F'], | |
'E': ['B', 'G'], | |
'F': ['B', 'C', 'D'], | |
'G': ['A', 'E'], | |
'H': ['C'] | |
} | |
print 'dfs', dfs(graph, 'A') | |
print 'bfs', bfs(graph, 'A') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment