Skip to content

Commit ce5990a

Browse files
committed
Celebrity Problem
1 parent 0ff4d11 commit ce5990a

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Stack/CelebrityProblem.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
using namespace std;
5+
6+
int getCelebrity(vector<vector<int>> arr)
7+
{
8+
stack<int> s;
9+
int n = arr.size();
10+
11+
for (int i = 0; i < n; i++)
12+
{
13+
s.push(i); // push all index value
14+
}
15+
16+
while (s.size() > 1)
17+
{
18+
int i = s.top();
19+
s.pop();
20+
21+
int j = s.top();
22+
s.pop();
23+
24+
if (arr[i][j] == 0)
25+
{
26+
s.push(i);
27+
}
28+
else
29+
{
30+
s.push(j);
31+
}
32+
}
33+
34+
int celeb = s.top();
35+
36+
for (int i = 0; i < n; i++)
37+
{
38+
if ((i != celeb) && (arr[i][celeb] == 0 || arr[celeb][i] == 1))
39+
{
40+
return -1; // no celebrity exits
41+
}
42+
}
43+
44+
return celeb;
45+
}
46+
47+
int main()
48+
{
49+
vector<vector<int>> arr = {{0, 1, 0}, {0, 0, 0}, {0, 1, 0}};
50+
51+
int ans = getCelebrity(arr);
52+
53+
cout << "Celebrity is : " << ans << endl;
54+
55+
return 0;
56+
}

Stack/CelebrityProblem.exe

120 KB
Binary file not shown.

0 commit comments

Comments
 (0)