Created
March 14, 2022 19:07
-
-
Save parkerziegler/405ddfc1514ac007f8d9baa86e4fcb6b to your computer and use it in GitHub Desktop.
A concise implementation of breadth-first search (BFS) in Python.
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
""" | |
Assume we have a graph modeled as a dictionary like so: | |
graph = { | |
'a': ['b', 'c'], | |
'b': ['d'], | |
'c': ['e'], | |
'd': ['f'], | |
'e': [], | |
'f': [] | |
} | |
bfs will traverse this graph using breadth-first search. | |
""" | |
from collections import deque | |
def bfs(graph, source): | |
queue = deque([source]) | |
while len(queue) > 0: | |
# Remove an element from the queue. | |
current = queue.popleft() | |
print(current) | |
for neighbor in graph[current]: | |
queue.append(neighbor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment