Which Data Structure Is Used for Breadth First Search of a Graph?

//

Larry Thompson

In graph theory, the Breadth First Search (BFS) algorithm is used to traverse or search a graph. It explores all the vertices of a graph in a breadthward motion, starting from a given source vertex. BFS uses a specific data structure called a queue to determine the order in which vertices are visited.

Queue Data Structure

A queue is an abstract data type that follows the FIFO (First-In-First-Out) principle. It maintains two operations: enqueue, which adds an element to the end of the queue, and dequeue, which removes an element from the front of the queue.

In BFS, we enqueue each unvisited neighbor of a vertex before moving on to its next neighbor. This ensures that vertices closer to the source vertex are visited first.

Pseudocode for BFS using Queue

To illustrate how BFS works with a queue, let’s consider the following pseudocode:


function BFS(graph, source):
    create an empty queue
    enqueue source into the queue
    mark source as visited
    
    while queue is not empty:
        dequeue a vertex v from the queue
        visit v
        
        for each unvisited neighbor w of v:
            enqueue w into the queue
            mark w as visited

Example Implementation

Let’s see how this works with an example graph:


graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

If we start BFS from vertex ‘A’, the order of visiting the vertices will be:

  • A
  • B
  • C
  • D
  • E
  • F

Visualization of BFS using a Queue

Let’s visualize the BFS algorithm using a queue:


Queue: A
Visited: A

Queue: B, C
Visited: A, B

Queue: C, D, E
Visited: A, B, C

Queue: D, E, F
Visited: A, B, C, D

Queue: E, F
Visited: A, B, C, D, E

Queue: F
Visited: A, B, C, D, E ,F

As you can see in the visualization above, BFS explores all vertices at the same level before moving to the next level. This makes it suitable for finding the shortest path between two vertices in an unweighted graph.

Conclusion

In summary, a queue is used as the data structure for Breadth First Search (BFS) of a graph. It ensures that vertices are visited in a breadthward manner and helps in maintaining the order of exploration. Understanding this concept is crucial for implementing and comprehending BFS algorithms.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy