How it works?
Lesson 3 of 9 in Coddy's Breadth-First Search - Graph Algorithms course.
BFS keeps a visited marker per vertex and a queue of vertices to process.
Step-by-Step Process:
- Mark the start visited and enqueue it.
- Dequeue the front vertex and record it in the visit order.
- For each unvisited neighbor (ascending), mark it visited and enqueue it. Marking on enqueue keeps a vertex from being added twice.
- Repeat until the queue is empty.
Example on vertices 0..3 with edges [0,1, 0,2, 1,3, 2,3], starting at 0:
- Visit 0, enqueue 1 and 2; visit 1, enqueue 3; visit 2; visit 3.
- Visit order: [0, 1, 2, 3] (compare with DFS: [0, 1, 3, 2]).
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)