Skip to content

Instantly share code, notes, and snippets.

@heygema
Created April 3, 2017 20:40
Show Gist options
  • Save heygema/a824e5b1924e05214a47f2e0c5408046 to your computer and use it in GitHub Desktop.
Save heygema/a824e5b1924e05214a47f2e0c5408046 to your computer and use it in GitHub Desktop.
Simple Python Implementing Breadth First Search Algorithm., enlightenment from here https://pythoninwonderland.wordpress.com/2017/03/18/how-to-implement-breadth-first-search-in-python/
graph = {
'A': ['B', 'C', 'E'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B', 'D'],
'F': ['C'],
'G': ['C']
}
def bfs_connected_graph(graph, start, goal):
# keeping track visited
visited = []
queue = [[start]]
if start == goal:
"completed"
while queue:
print ("queue %r" % queue)
# pop the first from queue
path = queue.pop(0)
print ("path : %r" % path)
node = path[-1]
print ("node %r" % node)
if node not in visited:
visited.append(node)
print ("visited node: %r" % visited)
neighbours = graph[node]
print ("neighbours {}".format(neighbours))
for n in neighbours:
new_path = list(path)
new_path.append(n)
queue.append(n)
if n == goal:
return print("finished %r" % new_path)
visited.append(node)
return "does not exist"
if __name__ == '__main__':
start = input('choose starting graph ?[A-G](capitalize) > ')
goal = input('choose your goal ?[A-G](capitalize) > ')
bfs_connected_graph(graph, start, goal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment