forked from varnitsingh/OJ-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS(SSSP).cpp
60 lines (51 loc) · 1.02 KB
/
BFS(SSSP).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
59
60
#include <bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define ll long long int
#define vi vector<int>
#define vii vector<int, int>
#define vc vector<char>
#define vl vector<ll>
#define mod 1000000007
#define INF 1000000009
using namespace std;
vi adj[100005];
bool vis[100005];
int length[100005];
void bfs(int node) {
queue<int> q;
q.push(node);
length[node] = 0;
int curr;
while(!q.empty()) {
curr =q.front(); q.pop();
vis[curr] = 1;
for(int child : adj[curr]) {
if(!vis[child]) {
length[child] = length[curr]+1;
q.push(child);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m;
cin >> n >> m;
int a, b;
for(int i = 1; i <= m; i++) {
cin >> a >> b;
adj[a].PB(b);
adj[b].PB(a);
}
bfs(3);
for(int i = 1; i <= n; i++) {
cout << length[i] << " ";
}
return 0;
}