forked from hacktoberfest2k20/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.cpp
41 lines (36 loc) · 881 Bytes
/
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
#include<bits/stdc++.h>
using namespace std;
//Breadth First Implementation
// Time Complexity = (V+E) where V = number of vertices and E = number of edges
vector<bool> visited;
void breadth_first_search(queue<int>&q,vector<vector<int>>&graph)
{
while(!q.empty())
{
cout<<q.front()<<endl;
int v = q.front();
visited[v] = true;
q.pop();
for(int u : graph[v])
{
if(!visited[u])q.push(u);
}
}
}
int main()
{
int vertices,edges; // assuming vertices start from 0 i.e 0,1,2,......
cin>>vertices>>edges;
visited.resize(vertices);
vector<vector<int>>graph(vertices);
for(int i =0;i<edges;i++)
{
int x,y;
cin>>x>>y;
graph[x].push_back(y);
}
queue<int>q;
q.push(0); //starting vertex is 0
breadth_first_search(q,graph);
return 0;
}