-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcelebrity problem
More file actions
63 lines (53 loc) · 1.85 KB
/
celebrity problem
File metadata and controls
63 lines (53 loc) · 1.85 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
/*
You are in a party of N people, where only one person is known to everyone. Such a person may be present in the party, if yes, (s)he
doesn’t know anyone in the party. Your task is to find the stranger (celebrity) in party.You will be given a square matrix M[][] where if
an element of row i and column j is set to 1 it means ith person knows jth person. You need to complete the function getId() which finds
the id of the celebrity if present else return -1. The function getId() takes two arguments, the square matrix M and its size N.
Note: Expected time complexity is O(N) with constant extra space.
Input:
The first line of input contains an element T denoting the number of test cases. Then T test cases follow. Each test case consist of 2
lines. The first line of each test case contains a number denoting the size of the matrix M. Then in the next line are space separated
values of the matrix M.
Output:
For each test case output will be the id of the celebrity if present (0 based index). Else -1 will be printed.
User Task:
The task is to complete the function getId() which returns the Id of celebrity if present, else -1.
Constraints:
1 <= T <= 50
2 <= N <= 501
0 <= M[][] <= 1
Example:
Input (To be used only for expected output) :
2
3
0 1 0 0 0 0 0 1 0
2
0 1 1 0
Output :
1
-1
Explanation :
For the above test case the matrix will look like
0 1 0
*/
bool knows(int a[MAX][MAX] , int i, int j){
return a[i][j]==1? true: false;
}
int getId(int a[MAX][MAX], int n)
{
int candidate=0;
for(int i=1; i<n&&candidate<n-1; i++){
if(knows(a,candidate,i)){
candidate=i;
}
}
for(int k=0; k<n; k++){
if(k!=candidate && (!knows(a,k,candidate) || knows(a,candidate,k))){
return -1;
}
}
return candidate;
}
0 0 0
0 1 0
Here, the celebrity is the person with index 1 ie id 1