-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1791-Find_Center_of_Star_Graph.cpp
More file actions
80 lines (72 loc) · 1.85 KB
/
1791-Find_Center_of_Star_Graph.cpp
File metadata and controls
80 lines (72 loc) · 1.85 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*******************************************************************************
* 1791-Find_Center_of_Star_Graph.cpp
* Billy.Ljm
* 27 June 2024
*
* =======
* Problem
* =======
* https://leetcode.com/problems/find-center-of-star-graph/
*
* There is an undirected star graph consisting of n nodes labeled from 1 to n.
* A star graph is a graph where there is one center node and exactly n - 1
* edges that connect the center node with every other node.
*
* You are given a 2D integer array edges where each edges[i] = [ui, vi]
* indicates that there is an edge between the nodes ui and vi. Return the
* center of the given star graph.
*
* ===========
* My Approach
* ===========
* We just have to compare 2 edges and the center node will be the only node
* that is present in both edges
*
* This has a time complexity of O(1) and space complexity of O(1).
******************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
int findCenter(vector<vector<int>>& edges) {
if (edges[0][0] == edges[1][0] or edges[0][0] == edges[1][1]) {
return edges[0][0];
}
else {
return edges[0][1];
}
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
vector<vector<int>> edges;
// test case 1
edges = { {1,2},{2,3},{4,2} };
std::cout << "findCenter(" << edges << ") = ";
std::cout << sol.findCenter(edges) << std::endl;
// test case 2
edges = { {1,2},{5,1},{1,3},{1,4} };
std::cout << "findCenter(" << edges << ") = ";
std::cout << sol.findCenter(edges) << std::endl;
return 0;
}