Last active
May 31, 2019 03:46
-
-
Save MrKich/8667682 to your computer and use it in GitHub Desktop.
Python BFS
This file contains hidden or 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 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'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a way your code can work for start=end? In order to find closed loops.