Skip to content

Commit f93d6b5

Browse files
Create CelebrityProblem
1 parent d57ef25 commit f93d6b5

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Stacks/Problems/CelebrityProblem

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import java.util.*;
2+
3+
class CelebrityProblem{
4+
5+
static int isCelebrity(int[][] mat, int n){
6+
7+
Stack<Integer> stk = new Stack<>();
8+
9+
for(int i = 0; i<n; i++){
10+
stk.push(i);
11+
}
12+
13+
while(stk.size()>1){
14+
int a = stk.pop();
15+
int b = stk.pop();
16+
if(mat[a][b]==1){
17+
stk.push(b);
18+
}
19+
else{
20+
stk.push(a);
21+
}
22+
}
23+
int candidate = stk.pop();
24+
for(int i = 0; i<n; i++){
25+
if(i!=candidate && (mat[candidate][i] == 1 || mat[i][candidate] == 0)){
26+
return -1;
27+
}
28+
}
29+
30+
return candidate;
31+
}
32+
33+
public static void main(String[] args){
34+
Scanner input = new Scanner(System.in);
35+
int n = input.nextInt();
36+
int[][] mat = new int[n][n];
37+
for(int i = 0; i<n; i++){
38+
for(int j = 0; j<n; j++){
39+
mat[i][j] = input.nextInt();
40+
}
41+
}
42+
System.out.println(isCelebrity(mat, n));
43+
}
44+
}

0 commit comments

Comments
 (0)