Breadth First Search

Distribute Education like Computer Geek

Breadth First Search (BFS) Algorithm

.

Definition
  • Breadth First Search (BFS) is an algorithm used for traversing or searching tree or graph data structures.
  • BFS splits all the vertices into two categories – Visited and Unvisited. 
  • It starts (visit) from a selected source vertex and visits all neighbouring vertices of the source vertex first before moving on to the next level vertices.
Breadth First Search diagram
Breadth First Search
  • BFS traverse vertices in a level-by-level manner, ensuring that vertices closer to the source vertex are visited before those farther away.

Breadth First Search

.

In diagram (A), we visited the source vertex or root vertex 1.

In diagram (B), we visited all the neighbouring vertices of source node numbered 1.

In diagram (C), we visited all the neighbouring vertices of nodes numbered 2.

In diagram (D), we visited all the neighbouring vertices of nodes numbered 3.

Note – Both the diagram represents the same Breadth First Search.
  • It utilizes a queue data structure to keep track of the vertices to be visited next.
  • BFS ensures that all vertices reachable from the source vertex are visited and processed.

.

Imagine you’re in a maze, and you want to find the shortest path from your starting point to the exit. With BFS, you would explore all the paths at the current layer before moving to the next layer. This means you’d first explore all adjacent nodes, then their adjacent nodes, and so on, until you find the exit or the destination.

Konrad Zuse developed Breadth First Search (BFS) Algorithm and used for locating related components of graphs in 1945, but his (rejected) Ph.D. thesis on the Plankalkül programming language was not published until 1972.
Edward F. Moore recreated it in 1959 and used it to determine the shortest path out of a maze. 
C. Y. Lee then developed it into a wire routing method, which was published in 1961.

.

Algorithm of Breadth First Search (BFS)

Input – Graph G and starting vertex A

Output – Visited vertices in BFS order

Input – Graph G and starting vertex A

Output – Visited vertices in BFS order

1.

Create an empty queue Q.

2.

Enqueue the starting vertex s into Q and mark it as visited and change the color from white to grey.

3.

While Q is not empty –

 

1.

Dequeue a vertex u from Q.

 

2.

Visit and process vertex u.

 

3.

For each unvisited neighbour v of u

  

·      Enqueue v into Q.

  

·      Mark v as visited & change color to grey.

  

·      Change color of u to black.

4.

Repeat steps 3 until Q becomes empty.

.

Example

Consider a simple graph with nodes A, B, C, D, E, F, G, H.

Starting from node A, BFS would explore nodes layer by layer.

White – Indicates the vertex has not been visited.

Grey – Indicates the vertex is currently being visited.

Black – Indicates the vertex and all its neighbours have been visited.

Step 1 – Enqueue the starting vertex A into Q and mark it as visited and change the color from white to grey.

Breadth First Search iteration 1

.

Step 2 – While Q is not empty – Dequeue vertex A from Q. Visit and process vertex A. For each unvisited neighbour {B, H} of A.

  • Enqueue {B, H} into Q.
  • Mark them as visited & change color to grey.
  • Change color of A to black.

Breadth First Search iteration 2

.

Step 3 – While Q is not empty – Dequeue vertex B from Q. Visit and process vertex B. For each unvisited neighbour {C, F, G} of A.

  • Enqueue {C, F, G} into Q.
  • Mark them as visited & change color to grey.
  • Change color of B to black.

Breadth First Search iteration 3

.

Step 4 – While Q is not empty – Dequeue vertex H from Q. Visit and process vertex H and it has no unvisited neighbour.

  • Change color of H to black.

Breadth First Search iteration 4

.

Step 5 – While Q is not empty – Dequeue vertex C from Q. Visit and process vertex C and it has no unvisited neighbour.

  • Change color of C to black.

Breadth First Search iteration 5

.

Step 6 – While Q is not empty – Dequeue vertex F from Q. Visit and process vertex F. For each unvisited neighbour {E, C, G} of F. C & G are already in the queue so neglect them.

  • Enqueue {E} into Q.
  • Mark it as visited & change color to grey.
  • Change color of F to black.

Breadth First Search iteration 6

.

Step 7 – While Q is not empty – Dequeue vertex G from Q. Visit and process vertex G and it has no unvisited neighbour.

  • Change color of G to black.

Breadth First Search iteration 7

.

Step 8 – While Q is not empty – Dequeue vertex E from Q. Visit and process vertex E. For each unvisited neighbour {D} of E.

  • Enqueue {D} into Q.
  • Mark it as visited & change color to grey.
  • Change color of E to black.

Breadth First Search iteration 8

.

Step 9 – While Q is not empty – Dequeue vertex D from Q. Visit and process vertex D and it has no unvisited neighbour.

  • Change color of D to black.

Breadth First Search iteration 9

Source Code of Breadth First Search
Time Complexity

In the worst-case scenario, the time complexity of the Breadth First Search (BFS) algorithm is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

In the worst case, each vertex is visited once, and each edge is traversed once.

Visiting a vertex and traversing an edge both take constant time, assuming that the graph is represented using an adjacency list or matrix.

.

Space Complexity

The space complexity of BFS is O(V), where V is the number of vertices. This is because it requires additional queue to store the visited nodes and the queue.

.

Advantages
  1. It exhaustively explores all vertices at each level of the graph, ensuring that no vertices are missed.
  2. It typically uses a queue data structure to maintain the order of vertices to be visited.
  3. It does not use recursion, making it less prone to stack overflow errors.
  4. It guarantees finding the shortest path between the starting vertex and any other reachable vertex in an unweighted graph.

.

Disadvantages
  1. Requires more memory as it stores all visited nodes.
  2. Inefficient for large graphs or graphs with complex structures.
  3. In weighted graphs, where edges have different weights or costs, BFS may not find the shortest path due to its greedy nature.

.

Applications
  1. Shortest path finding
  2. Web crawling
  3. Social network analysis
  4. Minimum spanning tree algorithms
  5. Solving puzzles like the 15-puzzle
  6. Finding connected components in an undirected graph
  7. Network flow analysis
  8. Bipartite graph detection
  9. Wireless sensor network routing
  10. Maze solving
  11. Level-order traversal of trees
  12. Analyzing and optimizing game states in artificial intelligence

Test Yourself

Q1- Can BFS find the shortest path in a weighted graph? Why or why not?

No, BFS cannot find the shortest path in a weighted graph because it assumes all edges have the same weight. In a weighted graph, where edges have different weights or costs, BFS may not find the optimal path.

Q2- Is BFS more memory-efficient than DFS? Explain.

In general, BFS requires more memory than DFS because it stores all the visited vertices in a queue. However, in certain scenarios or graph structures, DFS may require more memory due to its recursive nature and deep call stack.

Q3- Can BFS be used to detect cycles in a graph?

No, BFS alone cannot be used to detect cycles in a graph because it does not maintain information about back edges. However, BFS can be combined with other algorithms or techniques to detect cycles in a graph efficiently.

Q4- Explain the Breadth First Search (BFS) algorithm and its working principle.

Breadth First Search (BFS) is an algorithm used for traversing or searching tree or graph data structures. It starts from a selected source vertex and visits all neighboring vertices of the source vertex first before moving on to the next level vertices.

Q5- Explain how BFS can be used for web crawling.

BFS can be used for web crawling by treating web pages as vertices and hyperlinks as edges. It starts from a seed URL, visits all linked pages at the same level, and then moves to the next level, ensuring a systematic and comprehensive exploration of the web.

Q6- Describe the steps involved in implementing BFS using a queue data structure.

The steps involve initializing a queue, enqueueing the starting vertex, dequeuing vertices, visiting and processing each vertex, and enqueuing its unvisited neighbours.

Q7- How does BFS ensure completeness in traversing a graph?

BFS ensures completeness by systematically exploring all vertices reachable from the starting vertex, ensuring that no vertices are missed during traversal.

Q8- What is the time complexity of Breadth First Search (BFS) in terms of vertices (V) and edges (E)?
   1. O(V)
   2. O(E)
   3. O(V + E)
   4. O(V * E)

Ans – (3)

Explanation – BFS traverses each vertex and edge once, leading to a time complexity of O(V + E).

Q9- Which data structure is commonly used in BFS for maintaining the order of vertices to be visited?
   1. Stack
   2. Heap
   3. Queue
   4. Set

Ans – (3)

Q10- Which property of BFS guarantees finding the shortest path in unweighted graphs?
   1. Completeness
   2. Optimality
   3. Memory Efficiency
   4. Scalability

Ans – (2) 

Q11- What is the space complexity of BFS in terms of the number of vertices (V)?
   1. O(1)
   2. O(V)
   3. O(V + E)
   4. O(V * E)

Ans – (2)

Q12- Which step is NOT involved in the BFS algorithm?
   1. Enqueuing the starting vertex
   2. Dequeuing a vertex
   3. Marking vertices as processed
   4. Popping a vertex from the stack

Ans – (4)

Explanation – Stack is not used in the BFS. Queue is used.

BOOKS

Algorithm T H CoremanAlgorithm by Udit AgarwalAlgorithm Ellis HorowitzData Structure & Algorithm Made Easy Narasimha

Â