Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

TECHIE DELIGHT </> 

FAANG Interview Preparation Practice

Data Structures and Algorithms 

Breadth-First Search (BFS) – Iterative and Recursive


Implementation

Breadth–first search (BFS) is an algorithm for traversing or searching tree or graph


data structures. It starts at the tree root (or some arbitrary node of a graph,

sometimes referred to as a ‘search key’) and explores the neighbor nodes first
before moving to the next-level neighbors.

The following graph shows the order in which the nodes are discovered in BFS:

Breadth–first search (BFS) is a graph traversal algorithm that explores vertices in the order of

their distance from the source vertex, where distance is the minimum length of a path from the

source vertex to the node as evident from the above example.

This website uses cookies. By using this site you agree to the use of cookies, our
Applications of BFS
policies, copyright terms and other conditions. Read our
Privacy Policy. Accept and Close
Copying garbage collection, Cheney’s algorithm.

Finding the shortest path between two nodes u and v , with path length measured by

the total number of edges (an advantage over depth–first search).

Testing a graph for bipartiteness.

Minimum Spanning Tree for an unweighted graph.

Web crawler.

Finding nodes in any connected component of a graph.

Ford–Fulkerson method for computing the maximum flow in a flow network.

Serialization/Deserialization of a binary tree vs. serialization in sorted order allows the

tree to be reconstructed efficiently.

Iterative Implementation of BFS


The non-recursive implementation of BFS is similar to the non-recursive implementation of DFS

but differs from it in two ways:

It uses a queue instead of a stack.

It checks whether a vertex has been discovered before pushing the vertex rather than

delaying this check until the vertex is dequeued.

The algorithm can be implemented as follows in C++, Java, and Python:

C++

1 #include <iostream>
2 #include <queue>
3 #include <vector>
4 using namespace std;
5  
6 // Data structure to store a graph edge
7 struct Edge {
8     int src, dest;
9 };
10  
11 // A class to represent a graph object
12 class Graph
13 {
14 public:
15     // a vector of vectors to represent an adjacency list
16     vector<vector<int>> adjList;
17  
18     // Graph Constructor
This website uses cookies. By using this site you agree to the use of cookies, our
19     Graph(vector<Edge> const &edges, int n)
policies, copyright terms and other conditions. Read our
Privacy Policy. Accept and Close
20     {
21         // resize the vector to hold `n` elements of type `vector<i
22         adjList.resize(n);
23  
24         // add edges to the undirected graph
25         for (auto &edge: edges)
26         {
27             adjList[edge.src].push_back(edge.dest);
28             adjList[edge.dest].push_back(edge.src);
29         }
30     }
31 };
32  
33 // Perform BFS on the graph starting from vertex `v`
34 void BFS(Graph const &graph, int v, vector<bool> &discovered)
35 {
36     // create a queue for doing BFS
37     queue<int> q;
38  
39     // mark the source vertex as discovered
40     discovered[v] = true;
41  
42     // enqueue source vertex
43     q.push(v);
44  
45     // loop till queue is empty
46     while (!q.empty())
47     {
48         // dequeue front node and print it
49         v = q.front();
50         q.pop();
51         cout << v << " ";
52  
53         // do for every edge (v, u)
54         for (int u: graph.adjList[v])
55         {
56             if (!discovered[u])
57             {
58                 // mark it as discovered and enqueue it
59                 discovered[u] = true;
60                 q.push(u);
61             }
62         }
63     }
64 }
65  
66 int main()
67 {
68     // vector of graph edges as per the above diagram
69     vector<Edge> edges = {
70         {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {5, 9},
71         {5, 10}, {4, 7}, {4, 8}, {7, 11}, {7, 12}
72         // vertex 0, 13, and 14 are single nodes
73     };
74  
75     // total number of nodes in the graph (labelled from 0 to 14)
76     int n = 15;
77  
78     // build a graph from the given edges
This 79     Graph
website graph(edges,
uses cookies. n);
By using this site you agree to the use of cookies, our
policies,
80 copyright
  terms and other conditions. Read our
Privacy Policy. Accept and Close
81     // to keep track of whether a vertex is discovered or not
82     vector<bool> discovered(n, false);
83  
84     // Perform BFS traversal from all undiscovered nodes to
85     // cover all connected components of a graph
86     for (int i = 0; i < n; i++)
87     {
88         if (discovered[i] == false)
89         {
90             // start BFS traversal from vertex `i`
91             BFS(graph, i, discovered);
92         }
93     }
94  
95     return 0;
96 }

Download   Run Code

Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Java

Python

Recursive Implementation of BFS


The recursive algorithm can be implemented as follows in C++, Java, and Python:

C++

1 #include <iostream>
2 #include <queue>
3 #include <vector>
4 using namespace std;
5  
6 // Data structure to store a graph edge
7 struct Edge {
8     int src, dest;
9 };
10  
11 // A class to represent a graph object
12 class Graph
13 {
14 public:
This 15
website uses cookies.
    // By using
a vector of this site youto
vectors agree to the use an
represent of cookies, our list
adjacency
policies, copyright terms and other conditions. Read our
Privacy Policy. Accept and Close
16     vector<vector<int>> adjList;
17  
18     // Graph Constructor
19     Graph(vector<Edge> const &edges, int n)
20     {
21         // resize the vector to hold `n` elements of type `vector<i
22         adjList.resize(n);
23  
24         // add edges to the undirected graph
25         for (auto &edge: edges)
26         {
27             adjList[edge.src].push_back(edge.dest);
28             adjList[edge.dest].push_back(edge.src);
29         }
30     }
31 };
32  
33 // Perform BFS recursively on the graph
34 void recursiveBFS(Graph const &graph, queue<int> &q, vector<bool> &
35 {
36     if (q.empty()) {
37         return;
38     }
39  
40     // dequeue front node and print it
41     int v = q.front();
42     q.pop();
43     cout << v << " ";
44  
45     // do for every edge (v, u)
46     for (int u: graph.adjList[v])
47     {
48         if (!discovered[u])
49         {
50             // mark it as discovered and enqueue it
51             discovered[u] = true;
52             q.push(u);
53         }
54     }
55  
56     recursiveBFS(graph, q, discovered);
57 }
58  
59 int main()
60 {
61     // vector of graph edges as per the above diagram
62     vector<Edge> edges = {
63         {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {5, 9},
64         {5, 10}, {4, 7}, {4, 8}, {7, 11}, {7, 12}
65         // vertex 0, 13, and 14 are single nodes
66     };
67  
68     // total number of nodes in the graph (labelled from 0 to 14)
69     int n = 15;
70  
71     // build a graph from the given edges
72     Graph graph(edges, n);
73  
74     // to keep track of whether a vertex is discovered or not
75     vector<bool> discovered(n, false);
This 76   uses cookies. By using this site you agree to the use of cookies, our
website
policies,
77 copyright
    //terms and other
create conditions.
a queue Read our
Privacy
for doing BFS Policy. Accept and Close
78     queue<int> q;
79  
80     // Perform BFS traversal from all undiscovered nodes to
81     // cover all connected components of a graph
82     for (int i = 0; i < n; i++)
83     {
84         if (discovered[i] == false)
85         {
86             // mark the source vertex as discovered
87             discovered[i] = true;
88  
89             // enqueue source vertex
90             q.push(i);
91  
92             // start BFS traversal from vertex `i`
93             recursiveBFS(graph, q, discovered);
94         }
95     }
96  
97     return 0;
98 }

Download   Run Code

Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Java

Python

The time complexity of BFS traversal is O(V + E), where V and E are the total number of
vertices and edges in the graph, respectively. Please note that O(E) may vary between O(1)

and O(V2), depending on how dense the graph is.

Also See:

Breadth First Search (BFS) – Interview Questions & Practice Problems

 Graph, Queue
 Algorithm, Amazon, Breadth-first search, FIFO, Medium, Microsoft, Must Know, Recursive

This website uses cookies. By using this site you agree to the use of cookies, our
policies, copyright terms and other conditions. Read our
Privacy Policy. Accept and Close
Techie Delight © 2022 All Rights Reserved. | Privacy Policy | Terms of Service | Send feedback

This website uses cookies. By using this site you agree to the use of cookies, our
policies, copyright terms and other conditions. Read our
Privacy Policy. Accept and Close

You might also like