-
Notifications
You must be signed in to change notification settings - Fork 0
/
037_BFSGraph.cpp
42 lines (34 loc) · 954 Bytes
/
037_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
#include <bits/stdc++.h>
using namespace std;
vector<int> BFS(int V, vector<pair<int, int>> edges)
{
// Write your code here
vector<vector<int>> E(V);
for(auto edge: edges){
E[edge.first].push_back(edge.second);
E[edge.second].push_back(edge.first);
}
for(int i=0; i<V; i++){
sort(E[i].begin(), E[i].end());
}
vector<bool> visited(V, false);
vector<int> result;
for(int i=0; i<V; i++){
if(!visited[i]){
queue<int> Q;
Q.push(i);
visited[i]=true;
while(!Q.empty()){
int curr=Q.front(); Q.pop();
result.push_back(curr);
for(auto edge: E[curr]){
if(!visited[edge]){
Q.push(edge);
visited[edge]=true;
}
}
}
}
}
return result;
}