File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+
3+ using namespace std ;
4+
5+ void bfs (int node,vector<vector<int > > &adjlist,bool visited[]) {
6+ queue<int > q;
7+ q.push (node);
8+ visited[node]=true ;
9+ while (!q.empty ()) {
10+ int n = q.front ();
11+ q.pop ();
12+ cout<<n<<" " ;
13+ for (auto it: adjlist[n]) {
14+ if (!visited[it]) {
15+ q.push (it);
16+ visited[it]=true ;
17+ }
18+ }
19+ }
20+ return ;
21+ }
22+
23+ int main () {
24+
25+ int nodes,edges;
26+ cin>>nodes>>edges;
27+
28+ vector<vector<int > > adjlist (nodes+1 );
29+
30+ for (int i=0 ;i<edges;i++) {
31+ int src,des;
32+ cin>>src>>des;
33+ adjlist[src].push_back (des);
34+ adjlist[des].push_back (src);
35+ }
36+
37+ bool visited[nodes+1 ];
38+ for (int i=1 ;i<=nodes;i++) visited[i]=false ;
39+
40+ for (int i=1 ;i<=nodes;i++) {
41+ if (!visited[i]) {
42+ bfs (i,adjlist,visited);
43+ }
44+ }
45+ return 0 ;
46+
47+ }
You can’t perform that action at this time.
0 commit comments