Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
BFS using vectors & queue as per the algorithm of CLRS in C Program?
In CLRS book the BFS algorithm is described using vectors and queue. We have to implement that algorithm using C++ STL. Let us see the algorithm at first.
Algorithm
BFS(G, s) −
begin
for each vertex u in G.V - {s}, do
u.color := white
u.d := infinity
u.p := NIL
done
s.color := green
s.d := 0
s.p := NIL
Q := NULL
insert s into Q
while Q is not null, do
u = delete from Q
for each v in adjacent to u, do
if v.color = white
v.color := green
v.d := u.d + 1
v.p := u
insert v into Q
end if
done
u.color = dark_green
done
end
Example
#include#include #include using namespace std; vector colour; vector dist; vector par; void addEdge(vector g[], int u, int v) { //add edge to form the graph g[u].push_back(v); g[v].push_back(u); } void BFS(vector g[], int s) { queue q; q.push(s); //insert source dist[s] = 0; colour[s] = "gray"; while (!q.empty()) { int u = q.front(); //top element from queue, then delete it q.pop(); cout g[], int n) { colour.assign(n, "white"); //put as unvisited dist.assign(n, 0); par.assign(n, -1); for (int i = 0; i g[n]; addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 3); addEdge(g, 1, 4); addEdge(g, 2, 5); addEdge(g, 2, 6); BFSAlgo(g, n); }
Output
0 1 2 3 4 5 6
Advertisements
