-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCelebrity Problem Using stack
More file actions
70 lines (66 loc) · 1.64 KB
/
Celebrity Problem Using stack
File metadata and controls
70 lines (66 loc) · 1.64 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
class Solution
{
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 two elements and compare 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 candidate = s.top();//store that potential candidate
//step3: agar single element bacha hoga i.e potential celebrity
//verify it
bool rowCheck = false;
int zeroCount = 0;
for(int i =0;i<n; i++){
if(M[candidate][i] == 0){
zeroCount++;
}
}
// if all zeroes
if(zeroCount == n){
rowCheck = true;
}
//column check
bool colCheck = false;
int oneCount = 0;
for(int i=0;i<n;i++){
if(M[i][candidate] == 1){
oneCount++;
}
}
if(oneCount == n-1){
colCheck = true;
}
if(rowCheck == true && colCheck == true){
return candidate;
}
else{
return -1;
}
}
};