Breadth first search in C++

Table of Contents

Breath First Search is a graph traversal technique used in graph data structure. It goes through level-wise. Graph is tree like data structure. To avoid the visited nodes during the traversing of a graph, we use BFS.

In this algorithm, lets say we start with node x, then we will visit neighbours of x, then neighbours of neighbours of x and so on.


Algorithm

To traverse a graph using BFS, we use queue to store the nodes and array data structure to distinguish the unvisited nodes.

  • 1. Create empty queue and push unvisited vertex to it.
  • 2. Do following unless queue is empty.
    • 2.1 pop the element from queue
    • 2.2 Push unvisited adjacent nodes of the popped node into the queue.

Consider this graph

According to our algorithm

Hence all the vertices are visited, then the only pop operation is performed, and queue will be empty then.


Implementation:

Output:

Adjacency matrix:
0–>1–>2–>5
1–>0–>3
2–>0–>4–>3
3–>2–>5–>1
4–>2–>5
5–>4–>3–>0
BFS :
0 1 2 5 3 4

That’s all about Breadth first search in C++.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *