BFS code example
Example 1: BFS in c++
#include<iostream>
#include <list>
using namespace std;
class Graph
{
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}
void Graph::BFS(int s)
{
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}
Example 2: breadth first search
procedure BFS(G, start_v) is
2 let Q be a queue
3 label start_v as discovered
4 Q.enqueue(start_v)
5 while Q is not empty do
6 v := Q.dequeue()
7 if v is the goal then
8 return v
9 for all edges from v to w in G.adjacentEdges(v) do
10 if w is not labeled as discovered then
11 label w as discovered
12 w.parent := v
13 Q.enqueue(w)
Example 3: bfs
1 procedure BFS(G, root) is
2 let Q be a queue
3 label root as discovered
4 Q.enqueue(root)
5 while Q is not empty do
6 v := Q.dequeue()
7 if v is the goal then
8 return v
9 for all edges from v to w in G.adjacentEdges(v) do
10 if w is not labeled as discovered then
11 label w as discovered
12 Q.enqueue(w)
Example 4: bfs
vector <int> v[10] ;
int level[10];
bool vis[10];
void bfs(int s) {
queue <int> q;
q.push(s);
level[ s ] = 0 ;
vis[ s ] = true;
while(!q.empty())
{
int p = q.front();
q.pop();
for(int i = 0;i < v[ p ].size() ; i++)
{
if(vis[ v[ p ][ i ] ] == false)
{
level[ v[ p ][ i ] ] = level[ p ]+1;
q.push(v[ p ][ i ]);
vis[ v[ p ][ i ] ] = true;
}
}
}
}
Example 5: bfs
function breadthFirstSearch (Start, Goal)
{
enqueue(Queue,Start)
setVisited(start)
while notEmpty(Queue)
{
Node := dequeue(Queue)
if Node = Goal
{
return Node
}
for each Child in Expand(Node)
{
if notVisited(Child)
{
setVisited(Child)
enqueue(Queue, Child)
}
}
}
}
Example 6: bfs algorithm
function breadthFirstSearch (Start, Goal)
{
enqueue(Queue,Start)
setVisited(start)
while notEmpty(Queue)
{
Node := dequeue(Queue)
if Node = Goal
{
return Node
}
for each Child in Expand(Node)
{
if notVisited(Child)
{
setVisited(Child)
enqueue(Queue, Child)
}
}
}
}