Breadth-First Search (using Python)
Overview
- Steps
- Code
- Time Complexity
- Conclusion
- Reference
Steps
- Add the vertex to start the breadth-first search to the empty queue. Mark that vertex visited.
- Extract a vertex from the queue and add its neighbors to the queue if that isn’t marked visited.
- Repeat step 2 until the queue is empty.
Add the vertex to start the breadth-first search to the empty queue. Mark that vertex visited.(從A開始)
Extract a vertex from the queue and add its neighbors to the queue if that isn’t marked visited.
We mark the vertices, B and C as visited because we added these to the queue.
Then we mark vertices D and E visited because we added these to the queue.
We extract vertex C from the queue. However, we don’t have any vertex added to the queue because we’ve already visited all neighbors of vertex C.
We are going to extract vertices D and E, but we’ve also visited these neighbors before. So the queue is empty and we finish to search. Finally, we’ve visited all reachable vertices from vertex A. In other words, we’ve marked all vertices visited.
Code
1 |
|
Output
1 |
|
Time Complexity
O(|V|+|E|)
vertices: v = queue.popleft()
E is the set of the edges
Conclusion
The level holds distances from the vertex from which we start searching.
The distance from the vertex to itself is 0, of course, we initialize the level above.
The parent holds the vertex just added as a key and the vertex from which we reach to the vertex just added as a value.
Reference
Breadth-First Search (using Python)
https://bominc0624.dev/2023/07/09/Breadth-First-Search/