1
+ /* There is an undirected star graph consisting of n nodes labeled from 1 to n.
2
+ A star graph is an undirected graph that has n nodes in which one is center node and has exactly n - 1 edges.
3
+
4
+ Given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi.
5
+ Return the center of the given star graph.
6
+ 4
7
+ |
8
+ 2
9
+ / \
10
+ 1 3
11
+
12
+ Here 2 is the answer.
13
+
14
+ Approach: Store the nodes in vector that are connected to partciular node, if size of that vector equals to nodes-1 then
15
+ print it is the centre. */
16
+
17
+ #include < bits/stdc++.h>
18
+ using namespace std ;
19
+
20
+ int findCenter (vector<vector<int >>& edges)
21
+ {
22
+ int n=edges.size ()+1 ;
23
+
24
+ vector<int >l[n+1 ];
25
+
26
+ // Store the destintaion edges into source node vector
27
+ for (int i=0 ;i<edges.size ();i++)
28
+ {
29
+ l[edges[i][0 ]].push_back (edges[i][1 ]);
30
+ l[edges[i][1 ]].push_back (edges[i][0 ]);
31
+ }
32
+
33
+ // Check if vector size is equal to nodes-1, to find the center
34
+ int center;
35
+ for (int i=0 ;i<=n;i++)
36
+ {
37
+ if (l[i].size ()==n-1 )
38
+ center=i;
39
+ }
40
+ return center;
41
+ }
42
+
43
+ int main ()
44
+ {
45
+ int src,dest,no_of_edges;
46
+ cout<<" Enter number of edges" <<endl;
47
+ cin>>no_of_edges;
48
+ vector<vector<int >>edges;
49
+
50
+ for (int i=0 ;i<no_of_edges;i++)
51
+ {
52
+ vector<int >temp;
53
+
54
+ cout<<" Enter source of edge" <<endl;
55
+ cin>>src;
56
+ temp.push_back (src);
57
+ cout<<" Enter destination of edge" <<endl;
58
+ cin>>dest;
59
+ temp.push_back (dest);
60
+
61
+ edges.push_back (temp);
62
+ }
63
+ cout<<" Center Of Star Graph : " ;
64
+ cout<<(findCenter (edges));
65
+ return 0 ;
66
+ }
67
+
68
+
69
+ /*
70
+ INPUT:
71
+ Enter number of edges
72
+ 3
73
+ Enter source of edge
74
+ 1
75
+ Enter destination of edge
76
+ 2
77
+ Enter source of edge
78
+ 2
79
+ Enter destination of edge
80
+ 3
81
+ Enter source of edge
82
+ 4
83
+ Enter destination of edge
84
+ 2
85
+ OUTPUT:
86
+ Center Of Star Graph : 2
87
+
88
+ Time Complexity: O(no_of_edges)
89
+ Space Complexity: O(no_of_edges)
90
+ */
0 commit comments