AlgorithmsCodingDataStructuresGraphTheory
A breadth-first search is an algorithm to iterate through a graph
Breadth first search is useful when
- We want to find a shortest path with some property
- We want to perform a tree traversal
- We can’t use recursion!
Complexity:
Time: O(|V| + |E|)
Space: O(|V|)
Iterative
from collections import deque
visited = {}
def bfs(root):
queue = deque(root)
visited[root] = True
while(queue != []):
n = queue.popleft()
f(n)
if n is not None:
for neighbor in n.adjacent:
if not visited[neighbor]:
queue.append(neighbor)
visited[neighbor] = True