-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCelebrity_Problem.cpp
More file actions
68 lines (55 loc) · 1.45 KB
/
Copy pathCelebrity_Problem.cpp
File metadata and controls
68 lines (55 loc) · 1.45 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
APPROACH - STACKS ("GFG")
TC -->
SC -->
private:
bool knows(vector<vector<int> >& M, int a, int b, int n) {
if(M[a][b] == 1)
return true;
else
return false;
}
public:
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& M, int n)
{
stack<int> s;
//step1: push all element in stack
for(int i=0; i<n; i++) {
s.push(i);
}
//step2: get 2 elements and copare them
while(s.size() > 1) {
int a = s.top();
s.pop();
int b = s.top();
s.pop();
if(knows(M,a,b,n)){
s.push(b);
}
else
{
s.push(a);
}
}
int ans = s.top();
//step3: single element in stack is potential celeb
//so verify it
int zeroCount = 0;
for(int i=0; i<n; i++) {
if(M[ans][i] == 0)
zeroCount++;
}
//all zeroes
if(zeroCount != n)
return -1;
//column check
int oneCount = 0;
for(int i=0; i<n; i++) {
if(M[i][ans] == 1)
oneCount++;
}
if(oneCount != n-1)
return -1;
return ans;
}
};