Skip to content

Instantly share code, notes, and snippets.

@mwrites
Forked from daveweber/graphs.py
Last active September 20, 2018 05:33
Show Gist options
  • Save mwrites/9391d4d8d7ccb2078a4662a762d1a19f to your computer and use it in GitHub Desktop.
Save mwrites/9391d4d8d7ccb2078a4662a762d1a19f to your computer and use it in GitHub Desktop.
Breadth First and Depth First Search in Python
# https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/
def bfs(graph, start):
visited, queue = set(), [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
def bfs_paths(graph, start, end):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == end:
yield path + [next]
else:
queue.append((next, path + [next]))
def dfs(graph, start):
visited, stack = set(), [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex] - visited)
return visited
def dfs_paths(graph, start, end):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for next in graph[vertex] - set(path):
if next == end:
yield path + [next]
else:
stack.append((next, path + [next]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment