forked from nitind2411/hacktoberfest-2022-DSA-CP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS.cpp
29 lines (26 loc) · 749 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
vector<int> bfs(int V, vector<int> adj[])
{
vector<int> bfs_traversal;
vector<bool> vis(V, false);
for (int i = 0; i < V; ++i) {
// To check if already visited
if (!vis[i]) {
queue<int> q;
vis[i] = true;
q.push(i);
// BFS starting from ith node
while (!q.empty()) {
int g_node = q.front();
q.pop();
bfs_traversal.push_back(g_node);
for (auto it : adj[g_node]) {
if (!vis[it]) {
vis[it] = true;
q.push(it);
}
}
}
}
}
return bfs_traversal;
}