euisblue
1791. Find Center of Star Graph

C++ Solution 1: Adjacency List

Used Adjacency List to recreate the graph. Then, found which vertex has the max neigbor.

1class Solution { 2 public: 3 int findCenter(vector<vector<int>>& edges) { 4 const int V = edges.size() + 1; 5 vector<int> g[V]; 6 7 for(int i=0; i<V-i; ++i) { 8 int u = edges[i][0]; 9 int v = edges[i][1]; 10 11 g[u-1].push_back(v-1); 12 g[v-1].push_back(u-1); 13 } 14 15 int mx = -1; 16 int mxV = -1; 17 18 for(int i=0; i<V; ++i) { 19 int temp = g[i].size(); 20 if(temp > mx) { 21 mx = temp; 22 mxV = i+1; 23 } 24 } 25 26 return mxV; 27 } 28};

C++ Solution 2: Star graph

The fact that the given graph is a star graph, we only need to check first 2 edges and whichever vertex shows up twice, has to be the center.

1class Solution { 2 public: 3 int findCenter(vector<vector<int>>& edges) { 4 int v[] = {edges[0][0], edges[0][1], edges[1][0], edges[1][1]}; 5 return (v[0]==v[2] || v[0]==v[3]) ? v[0] : v[1]; 6 } 7};