-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.cpp
48 lines (37 loc) · 901 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mx 100000
ll node, edge;
vector<ll> dis(mx), parent(mx);
vector<bool> visited(mx, 0);
vector<vector<ll>> adj(mx);
void bfs(ll sNode) {
parent[sNode] = -1;
dis[sNode] = 0;
queue<ll> q;
q.push(sNode);
while(!q.empty()) {
ll cNode = q.front();
q.pop();
for (ll i = 0; i < adj[cNode].size(); i++) {
if (!visited[adj[cNode][i]]) {
parent[adj[cNode][i]] = cNode;
dis[adj[cNode][i]] = dis[cNode] + 1;
q.push(adj[cNode][i]);
}
}
visited[cNode] = 1;
}
}
int main() {
cin >> node >> edge;
for (ll i = 0; i < edge; i++) {
ll a, b;
cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a); // undirected edge
}
bfs(0); // single source
}