-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCelebrityProblem.cpp
59 lines (43 loc) · 1.08 KB
/
CelebrityProblem.cpp
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
#include<bits/stdc++.h>
using namespace std;
bool knows(int a, int b, vector<vector<int> >& M) {
return M[a][b];
}
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& mat)
{
int n = mat.size();
stack<int> st;
for (int i = 0; i < n; i++)
st.push(i);
while (st.size() > 1) {
int first = st.top();
st.pop();
int second = st.top();
st.pop();
if (knows(first, second, mat))
st.push(second);
else
st.push(first);
}
int candidate = st.top();
st.pop();
// Verification of a candidate with other remaining members :-
bool checkRow = true;
for(int i = 0; i<n; i++) {
if(mat[candidate][i] == 1) {
checkRow = false;
break; // No need to check further
}
}
bool checkCol = true;
for(int i = 0; i < n; i++) {
if(i != candidate && mat[i][candidate] == 0) {
checkCol = false;
break; // No need to check further
}
}
if(checkRow && checkCol)
return candidate;
return -1;
}