-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathThe_Celebrity_Problem.java
50 lines (45 loc) · 1.02 KB
/
The_Celebrity_Problem.java
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
// { Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
int N = sc.nextInt();
int M[][] = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
M[i][j] = sc.nextInt();
}
}
System.out.println(new Solution().celebrity(M, N));
t--;
}
}
}
class Solution {
int celebrity(int M[][], int n) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < n; i++) {
stack.push(i);
}
while (stack.size() != 1) {
int a = stack.pop();
int b = stack.pop();
if (M[a][b] == 1) {
stack.push(b);
} else {
stack.push(a);
}
}
int c = stack.pop();
for (int i = 0; i < n; i++) {
if (i != c && (M[i][c] != 1 || M[c][i] == 1)) {
return -1;
}
}
return c;
}
}