Skip to content

Instantly share code, notes, and snippets.

@MrKich
Last active May 31, 2019 03:46
Show Gist options
  • Save MrKich/8667682 to your computer and use it in GitHub Desktop.
Save MrKich/8667682 to your computer and use it in GitHub Desktop.
Python BFS
def bfs( start, end, graph ):
todo = [(start, [start])]
while len( todo ):
node, path = todo.pop( 0 )
for next_node in graph[node]:
if next_node in path:
continue
elif next_node == end:
yield path + [next_node]
else:
todo.append( (next_node, path + [next_node]) )
if __name__ == '__main__':
graph = { 'A': ['B','C'],
'B': ['D'],
'C': ['E'],
'D': ['E', 'F'],
'E': [] }
[ print( x ) for x in bfs( 'A', 'F', graph ) ]
# ['A', 'B', 'D', 'F']
@TheRazorace
Copy link

Is there a way your code can work for start=end? In order to find closed loops.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment