forked from zapellass123/OpenEmailGenerator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBFSGraph.cpp
58 lines (53 loc) · 1.26 KB
/
BFSGraph.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
typedef unsigned long long int ll;
using namespace std;
// V denotes the number of nodes
// adjList is the list with neighbours info
vector<int> BFSofGraph(int V, vector<int> adjList[])
{
int visitedNodes[V + 1] = {0}; // mark all as not visited;
visitedNodes[1] = 1;
queue<int> q;
q.push(1); // as it is one based indexing
vector<int> BFS;
while (!q.empty())
{
int node = q.front();
q.pop();
BFS.push_back(node);
for (auto it : adjList[node])
{
if (!visitedNodes[it])
{
visitedNodes[it] = 1;
q.push(it);
}
}
}
return BFS;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
vector<int> adjList[n + 1];
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
adjList[u].push_back(v);
// remove this line when it is directed graph and space complexity is O(E);
adjList[v].push_back(u);
}
vector<int> bfs = BFSofGraph(n, adjList);
for (auto it : bfs)
{
cout << it << " ";
}
}