Need help from an expert?
The world’s top online tutoring provider trusted by students, parents, and schools globally.
BFS (Breadth-First Search) is an algorithm used for graph traversal that explores all the vertices of a graph in breadth-first order.
BFS starts at a given vertex and explores all the vertices at the same level before moving on to the next level. It uses a queue data structure to keep track of the vertices that need to be visited. The algorithm works as follows:
1. Start at a given vertex and mark it as visited.
2. Add the vertex to a queue.
3. While the queue is not empty, do the following:
a. Dequeue a vertex from the queue.
b. Visit all the adjacent vertices of the dequeued vertex that have not been visited yet.
c. Mark each visited vertex as visited and add it to the queue.
BFS can be used to find the shortest path between two vertices in an unweighted graph. To do this, we can keep track of the distance from the starting vertex to each visited vertex. We can also keep track of the parent of each visited vertex, which allows us to reconstruct the shortest path from the starting vertex to any other vertex.
The time complexity of BFS is O(V+E), where V is the number of vertices and E is the number of edges in the graph. This is because BFS visits each vertex and each edge exactly once.
Study and Practice for Free
Trusted by 100,000+ Students Worldwide
Achieve Top Grades in your Exams with our Free Resources.
Practice Questions, Study Notes, and Past Exam Papers for all Subjects!
The world’s top online tutoring provider trusted by students, parents, and schools globally.