Pseudo Code
Lesson 4 of 9 in Coddy's Breadth-First Search - Graph Algorithms course.
bfs(n, edges, start):
build adjacency (sort each list ascending)
visited = all false
queue = [start]; visited[start] = true
order = []
while queue not empty:
node = queue.dequeue() # take from the FRONT
order.add(node)
for nb in adj[node]:
if not visited[nb]:
visited[nb] = true
queue.enqueue(nb)
return order- The only difference from DFS is the container: a queue (FIFO) instead of a stack (LIFO).
- An easy way to write the queue is an array with a moving head index: dequeue by reading
queue[head]and advancinghead.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Breadth-First Search - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)