-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTheCelebrityProblem.java
More file actions
40 lines (33 loc) · 935 Bytes
/
TheCelebrityProblem.java
File metadata and controls
40 lines (33 loc) · 935 Bytes
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
package Stacks;
import java.util.Stack;
public class TheCelebrityProblem {
int celebrity(int[][] M, int n) {
Stack<Integer> st = new Stack<>();
for (int i = 0; i < n; i++) {
st.push(i);
}
while (st.size() > 1) {
int v1 = st.pop();
int v2 = st.pop();
if (M[v1][v2] == 0) { // v1 might be a Hero.
st.push(v1);
} else if (M[v2][v1] == 0) { // v2 might be a Hero.
st.push(v2);
}
}
if (st.size() == 0)
return -1;
int potential = st.pop();
for (int j = 0; j < n; j++) {
if (M[potential][j] == 1)
return -1;
}
for (int i = 0; i < n; i++) {
if (i == potential)
continue;
if (M[i][potential] == 0)
return -1;
}
return potential;
}
}