Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<list>
- #include<queue>
- using namespace std;
- class graph{
- public:
- int v;
- list<int> *adj;
- graph(int vertex){
- v=vertex;
- adj=new list<int>[v];
- }
- void AddEdge(int v1,int v2){
- adj[v1].push_back(v2);
- }
- void BFS(int start){
- bool visit[v];
- for(int i=0;i<v;i++)
- visit[i]=false;
- queue<int>q;
- q.push(start);
- visit[start]=true;
- while(!q.empty()){
- int temp=q.front();
- q.pop();
- cout<<temp<<" ";
- list<int>::iterator t;
- for(t=adj[temp].begin();t!=adj[temp].end();t++){
- if(visit[*t]==false){
- visit[*t]=true;
- q.push(*t);
- }
- }
- }
- }
- };
- 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;
- }
Add Comment
Please, Sign In to add comment