-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
69 lines (61 loc) · 1.02 KB
/
Copy pathBFS.cpp
File metadata and controls
69 lines (61 loc) · 1.02 KB
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
59
60
61
62
63
64
65
66
67
68
69
#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
const ll N = 1e5+10;
vector<ll>g[N];
bool vis[N];
int level[N];
void bfs(ll source)
{
queue<ll>q;
q.push(source);
vis[source] = true;
while(!q.empty())
{
ll cur_v=q.front();
q.pop();
cout<<cur_v<<" ";
for(ll child : g[cur_v])
{
if(!vis[child])
{
q.push(child);
vis[child] = true;
level[child] = level[cur_v] + 1;
}
}
}
cout<<endl;
}
int main()
{
ll n ;
cin >> n ;
for (ll i = 0 ; i < n-1 ; i++)
{
ll v1, v2;
cin >> v1 >> v2 ;
g[v1].push_back(v2);
g[v2].push_back(v1);
}
bfs(1);
for (ll i = 1 ; i <= n ; i++)
{
cout<<i<<" : "<<level[i]<<endl;
}
}
// input
// 13
// 1 2
// 1 3
// 1 13
// 2 5
// 5 6
// 5 7
// 5 8
// 8 12
// 3 4
// 4 9
// 4 10
// 10 11
// 9 11