File tree 1 file changed +62
-0
lines changed
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ void printdata (vector<int > grph[],int v){
5
+ for (int i=0 ;i<v;i++){
6
+ cout<<i;
7
+ for (int p:grph[i]){
8
+ cout<<" ->" <<p;
9
+ }
10
+ cout<<endl;
11
+ }
12
+ }
13
+
14
+ void addata ( vector<int > grph[],int a, int b){
15
+ grph[a].push_back (b);
16
+ grph[b].push_back (a);
17
+ }
18
+ void BFS (vector<int > grph[],bool visited[],int s){
19
+ visited[s]=true ;
20
+ queue<int > q;
21
+ q.push (s);
22
+ while (!q.empty ()){
23
+ int k=q.front ();
24
+ cout<<q.front ()<<" " ;
25
+ for (int p:grph[k]){
26
+ if (visited[p]==false ){
27
+ visited[p]=true ;
28
+ q.push (p);
29
+ }
30
+ }
31
+ q.pop ();
32
+ }
33
+ }
34
+ void BFSdistinct (vector<int > grph[],int v){
35
+ bool visited[v];
36
+ int cnt=0 ;
37
+ for (int i=0 ;i<v;i++){
38
+ visited[i]=false ;
39
+ }
40
+ for (int i=0 ;i<v;i++){
41
+ if (visited[i]==false ){
42
+ BFS (grph,visited,i);
43
+ cnt++;
44
+ }
45
+ }
46
+ cout<<endl;
47
+ cout<<cnt<<endl;
48
+ }
49
+ int main (){
50
+ int v,e,a,b;
51
+ cout<<" Enter the number of vertices of in undirected graphs" <<endl;
52
+ cin>>v;
53
+ vector<int > grph[v];
54
+ cout<<" Enter the number of edges in graph" <<endl;
55
+ cin>>e;
56
+ for (int i=0 ;i<e;i++){
57
+ cin>>a>>b;
58
+ addata (grph,a,b);
59
+ }
60
+ printdata (grph,v);
61
+ BFSdistinct (grph,v);
62
+ }
You can’t perform that action at this time.
0 commit comments