Posted on by Kalkicode
Code Graph

Breadth first traversal for a Graph

In the realm of computer science and graph theory, the concept of traversing graphs is of paramount importance. Graphs are a fundamental data structure used to represent a set of objects, some of which are connected by links. Traversal of a graph involves visiting all the vertices and edges of the graph systematically. One of the common traversal algorithms is the Breadth First Traversal (BFS) algorithm, which systematically explores the vertices of a graph level by level.

Problem Statement and Description

Given a directed graph represented using an adjacency list, we aim to perform a Breadth First Traversal starting from a specific vertex. Breadth First Traversal is executed by visiting all the vertices reachable from the given starting vertex while moving to vertices at the same level before moving to the next level.


Let's consider a simple example to illustrate the problem. We have the following directed graph:

Breadth First Traversal for a Graph
0 -> 1, 5
1 -> 1
2 -> 1
3 -> 0, 3
4 -> 2, 3
5 -> 1

The numbers represent vertices, and the arrows indicate directed edges between vertices. If we start the BFS traversal from vertex 4, the traversal sequence will be: 4 -> 2 -> 3 -> 1 -> 0 -> 5.

Idea to Solve the Problem

To perform BFS on a graph, we use a queue data structure to keep track of the vertices to be visited. We start by enqueueing the starting vertex into the queue and mark it as visited. Then, while the queue is not empty, we dequeue a vertex, visit its adjacent vertices, enqueue them if they haven't been visited, and mark them as visited. We repeat this process until the queue is empty.


Here's a pseudocode representation of the BFS algorithm:

procedure BFS(graph, start):
    mark start as visited
    while queue is not empty:
        vertex = queue.dequeue()
        for each adjacent_vertex of vertex:
            if adjacent_vertex is not visited:
                mark adjacent_vertex as visited

Algorithm Explanation

  1. Initialize an empty queue and enqueue the starting vertex.
  2. Mark the starting vertex as visited.
  3. While the queue is not empty: a. Dequeue a vertex from the queue. b. Process the dequeued vertex (print or perform other operations). c. Traverse all adjacent vertices of the dequeued vertex: i. If an adjacent vertex is not visited, enqueue it and mark it as visited.

Code Solution

Time Complexity

The time complexity of the BFS algorithm depends on the number of vertices (V) and edges (E) in the graph. In the worst case, each vertex and edge are visited once, resulting in a time complexity of O(V + E). Since every vertex and edge are processed once, the algorithm is efficient for traversing large graphs.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment