Skip to content

Instantly share code, notes, and snippets.

@parkerziegler
Created March 14, 2022 19:07
Show Gist options
  • Save parkerziegler/405ddfc1514ac007f8d9baa86e4fcb6b to your computer and use it in GitHub Desktop.
Save parkerziegler/405ddfc1514ac007f8d9baa86e4fcb6b to your computer and use it in GitHub Desktop.
A concise implementation of breadth-first search (BFS) in Python.
"""
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