forked from omonimus1/geeks-for-geeks-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs-graph.cpp
29 lines (29 loc) · 821 Bytes
/
bfs-graph.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
// https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1/?track=md-graph&batchId=144
vector <int> bfs(vector<int> g[], int N) {
queue<int> qu;
vector<int> res;
// Create vector of N and set all of the them as false
vector<bool> vis(N, false);
// N is the root: starting point
qu.push(0);
// Set first root as visited
vis[0]=true;
// While queue q is not empty:
while(!qu.empty())
{
// Deque vertex from queue
int num=qu.front();
qu.pop();
// Enque all not yet visited adjancent
res.push_back(num);
for(auto it=g[num].begin(); it!=g[num].end();it++)
{
if(vis[*it]==false)
{
vis[*it]=true;
qu.push(*it);
}
}
}
return res;
}