-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbfs.cpp
More file actions
51 lines (38 loc) · 876 Bytes
/
bfs.cpp
File metadata and controls
51 lines (38 loc) · 876 Bytes
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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 1e5 + 5;
int n, m, parent[N];
vector<int> g[N];
bool visited[N];
int main() {
cout << "Enter n_nodes and n_edges: ", cin >> n >> m;
// Read input for graph
for (int i = 0; i < m; i++)
{
int n1, n2;
cin >> n1 >> n2;
g[n1].push_back(n2);
g[n2].push_back(n1);
}
queue<int> qu;
// Assume that the root is 1
qu.push(1);
visited[1] = true;
parent[1] = 1;
while (!qu.empty())
{
int current = qu.front();
qu.pop();
for (int neg : g[current]) {
if (!visited[neg]) {
qu.push(neg);
parent[neg] = current;
visited[neg] = true;
}
}
cout << current << endl;
}
return 0;
}