forked from hacktoberfest2k20/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreadth_first_search.cpp
More file actions
55 lines (51 loc) · 1.2 KB
/
breadth_first_search.cpp
File metadata and controls
55 lines (51 loc) · 1.2 KB
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
//Time complexity O(v) where v is the number of vertices in the graph
//Space complexity O(v)
/*Test case
6 7
0 1
0 2
0 3
1 3
1 4
2 3
2 5
*/
#include<bits/stdc++.h>
using namespace std;
void bfs(vector< vector<int> >graph, int root,int v)
{
vector<int>visited(v,0);//keeps track of visited nodes
queue<int>q;//queue used for bfs
q.push(root);//pushing the root to the queue
visited[root]=1;
while(!q.empty())
{
int a=q.front();
q.pop();
cout<<a<<"\n";
for(int i=0;i<graph[a].size();i++)
{
if(!visited[graph[a][i]])// pushing all the nodes that are not visited and are connected to the node a
{
q.push(graph[a][i]);
visited[graph[a][i]]=1;//marks the node as visited
}
}
}
}
int main()
{
int v,e;//v is the number of vertices or nodes and e is the number of edges
cin>>v>>e;
vector< vector<int> >graph;
graph.resize(v);
for(int i=0;i<e;i++) // this creates an adjacency list for the given graph
{
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
bfs(graph,0,v);
return 0;
}