-
-
Save mwrites/9391d4d8d7ccb2078a4662a762d1a19f to your computer and use it in GitHub Desktop.
Breadth First and Depth First Search 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
# 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