Skip to content

Instantly share code, notes, and snippets.

@sbsatter
Created August 20, 2016 07:20
Show Gist options
  • Save sbsatter/576f676f76fc51c076bc1bef7adea277 to your computer and use it in GitHub Desktop.
Save sbsatter/576f676f76fc51c076bc1bef7adea277 to your computer and use it in GitHub Desktop.
Geeks4Geeks celebrity problem
class GfG
{
// The task is to complete this function
int getId(int M[][], int n)
{
java.util.Stack<Integer> stack= new java.util.Stack<Integer>();
// Your code here
for(int i=0; i<n; i++){
stack.push(i);
}
int a= stack.pop();
int b= stack.pop();
while(stack.size()>01){
if(knows(M,a,b)){
a=stack.pop();
}else{
b=stack.pop();
}
}
int c=stack.pop();
if(knows(M,a,b) && !knows(M,b,a)){
c=b;
}else if(knows(M,b,a) && !knows(M,a,b)){
c=a;
}
for(int i=0; i<n; i++){
if(i!=c){
if(knows(M,c,i)|| !knows(M,i,c)){
return -1;
}
}
}
return c;
}
boolean knows(int [][] M, int a, int b){
return M[a][b]==1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment