Created
March 17, 2016 18:46
-
-
Save daveweber/99ea4da41f42ac92cdbf 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
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
In BFS you should use
collections.dequeue
instead of a list for the queue. Python's lists are implemented as vectors so when youqueue.pop(0)
that'sO(V)
instead ofO(1)
so you won't get theO(V + E)
run-time like BFS should have. I believe that this would beO(V^2 + E)
instead.