forked from TECHOUS/AlgoHeist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
54 lines (50 loc) · 1019 Bytes
/
BFS.cpp
File metadata and controls
54 lines (50 loc) · 1019 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int bfs(vector<int>adj[], int source,int v) {
queue<int> q;
bool boolean[v] = {false};
boolean[source] = true;
q.push(source);
while(q.size()!=0) {
int vert = q.front();
cout << vert << "->";
q.pop();
for (int i = 0; i < (adj[vert]).size(); ++i)
{
if(boolean[adj[vert][i]] == false){
q.push(adj[vert][i]);
boolean[adj[vert][i]] = true;
}
}
}
}
int main(){
int e,v,u,w,source;
cout << "enter number of edges: ";
cin >> e;
cout << "enter number of vertices: ";
cin >> v;
cout << "tell the vertices between which there exist an edge\n";
vector<int> adj[v];
for (int i = 0; i < e; ++i)
{
cin >> u >> w;
adj[u].push_back(w);
adj[w].push_back(u);
}
cout<<"enter the source node: ";
cin>>source;
cout<<endl<<"Adjacency list"<<endl;
for (int i = 0; i < v; ++i)
{
cout<<i<<" -> ";
for (int j = 0; j < adj[i].size(); ++j)
{
cout<<adj[i][j]<<" -> ";
}
cout<<endl;
}
cout<<endl;
bfs(adj,source,v);
cout<<endl;
}