Related data structure:
AlgorithmData_StructureGraphBFS
Breadth-First Search (BFS) is a near-to-far traversal method, starting from a certain node, always prioritising the visit to the nearest vertices and expanding outwards layer by layer.
Implementation
BFS is usually implemented with the help of a queue, the queue has first-in-first-out property.
- Add the starting vertex to the queue and start the loop
- In each iteration of the loop, pop the vertex at the front of the queue and record it as visited, then add all adjacent vertices of that vertex to the back of the queue
- Repeat step 2 until all vertices have been visited
Time complexity
All vertices will be queued and dequeued once, using time. During the process of traversing adjacent vertices in undirected graph, all edges will be visited twice, using time; the over all time complexity is .
Back to parent node: ADT - Graph
Reference: