Skip to content

Instantly share code, notes, and snippets.

@daveweber
Created March 17, 2016 18:46
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save daveweber/99ea4da41f42ac92cdbf to your computer and use it in GitHub Desktop.
Save daveweber/99ea4da41f42ac92cdbf to your computer and use it in GitHub Desktop.
Breadth First and Depth 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]))
@jondeaton
Copy link

jondeaton commented Sep 10, 2018

In BFS you should use collections.dequeue instead of a list for the queue. Python's lists are implemented as vectors so when you queue.pop(0) that's O(V) instead of O(1) so you won't get the O(V + E) run-time like BFS should have. I believe that this would be O(V^2 + E) instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment