BFS idea
- Algorithms course
- Intermediate
- Lesson 53/80
- 4 min
Explore layer by layer from a start vertex.
BFS layers
Breadth-first search (BFS) starts at a source vertex and spreads layer by layer outward.
Each layer processes all vertices one step further. This makes BFS give the path with the fewest edges in an undirected graph.
BFS is often used for shortest path and reachability problems; it is implemented with a queue.
Order priority
BFS adds a vertex's neighbors to the queue when processed. First in, first out (FIFO) applies.
This way vertices with smaller distance are always processed first; the order stays intact.
Adding happens at the back, removal at the front; this preserves the layer order.
Practice Print layers
Write bfs_order(graph, start). List vertices in BFS visit order and return it. Print [0, 1, 2, 3] with print(bfs_order({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0)).
Starter code
def bfs_order(graph, start):
# Return BFS visit orderSample solution
def bfs_order(graph, start):
# Return BFS visit order
visited = []
queue = [start]
while queue:
node = queue.pop(0)
if node not in visited:
visited.append(node)
for nb in graph[node]:
if nb not in visited:
queue.append(nb)
return visited
print(bfs_order({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0))Expected output
[0, 1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which data structure does BFS use?
- Stack
- Queue Correct answer
- Stack and queue
- Heap
Explanation: Queue.
2 BFS start
queue = [____]
queue = [start]
Explanation: start is right.
3 BFS idea: match the terms
| Term | Meaning |
|---|---|
BFS |
Layer |
queue |
FIFO |
DFS |
Deep |
heap |
Priority |