-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbfs.cpp
75 lines (67 loc) · 1.4 KB
/
bfs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// A c++ program to demonstrate BFS traveral on undirected graph
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int main()
{
int edges,a,b;
vector<int>nodes[1000];
cout<<"Enter the no of edges"<<endl;
cin>>edges;
for(int i=0;i<edges;i++){
cin>>a>>b;
nodes[a].push_back(b);
nodes[b].push_back(a);
}
cout<<endl;
//Adj list representation
for(int i=0;i<1000;i++)
{
if(!nodes[i].empty())
{ cout<<"[ "<<i<<" ]"<<"-->";
for(vector<int>::iterator it=nodes[i].begin();
it!=nodes[i].end();++it)
{
cout<<*it<<"-->";
}
cout<<"NULL"<<endl;
}
}
queue<int> que;
//initially que is empty
bool visited[1000];
// mark all the vertices as not visited
for(int i=0;i<1000;i++)
visited[i]=false;
int start;
cout<<"\nEnter the starting node"<<endl;
cin>>start;
//insert the starting node into the queue
que.push(start);
//mark the starting node as visited
visited[start]=true;
cout<<"\nBFS Traversal\n";
while(!que.empty())
{
//Dequeue a vertex from que and print it
int front = que.front();
cout<<front<<" ";
que.pop();
// get all adjacent vertices of the dequeued vertex s
// If an adjacent vertex has not been visited,
//then mark it as visited
// and enqueue it
for(vector<int>::iterator it=nodes[front].begin();
it!=nodes[front].end();++it)
{
if(visited[*it]==false)
{
visited[*it]=true;
que.push(*it);
}
}
}
cout<<endl;
return 0;
}