Name: Reg No:: BFS Algorithm
Name: Reg No:: BFS Algorithm
BFS algorithm
1)
#include <iostream>
#include <list>
class Graph
int numVertices;
list *adjLists;
bool* visited;
public:
Graph(int vertices);
};
Graph::Graph(int vertices)
numVertices = vertices;
adjLists[src].push_back(dest);
adjLists[dest].push_back(src);
visited[i] = false;
list queue;
visited[startVertex] = true;
queue.push_back(startVertex);
list::iterator i;
while(!queue.empty())
queue.pop_front();
if(!visited[adjVertex])
visited[adjVertex] = true;
queue.push_back(adjVertex);
}
}
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);
g.BFS(2);
return 0;
Output
2)
Depth First Search
#include<iostream>
#include<list>
using namespace std;
class Graph
{
int V;
list<int> *adj;
void DFSUtil(int v, bool visited[]);
public:
Graph(int V);
void addEdge(int v, int w);
void DFS(int v);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
DFSUtil(v, visited);
}
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);
return 0;
}
Output: