-
Notifications
You must be signed in to change notification settings - Fork 1
/
CelebrityProblem2.cpp
44 lines (36 loc) · 1010 Bytes
/
CelebrityProblem2.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
// https://www.geeksforgeeks.org/the-celebrity-problem/
#include <vector>
#include <iostream>
bool knows(std::vector<std::vector<int>>& matrix, int i, int j)
{
return matrix[i][j];
}
int findCelebrity(std::vector<std::vector<int>>& matrix)
{
int first = 0;
int last = matrix.size() - 1;
while (first < last) {
if (knows(matrix, first, last)) {
first++;
} else {
last--;
}
}
for (int i = 0; i < matrix.size(); ++i) {
if ((i != first) && knows(matrix, i, first) &&
!knows(matrix, i, first)) {
return -1;
}
}
return first;
}
int main()
{
std::vector<std::vector<int>> matrix {{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 0, 0},
{0, 0, 1, 0}};
int id = findCelebrity(matrix);
std::cout << "Celebrity index : " << id << "\n";
return 0;
}