Skip to content

Instantly share code, notes, and snippets.

@eloyz
Last active September 16, 2017 02:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eloyz/6991865 to your computer and use it in GitHub Desktop.
Save eloyz/6991865 to your computer and use it in GitHub Desktop.
Depth First Search and Breath First Search Algorithm http://youtu.be/zLZhSSXAwxI
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