File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
main/java/com/thealgorithms/stacks
test/java/com/thealgorithms/stacks Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .stacks ;
2+
3+ /**
4+ * Solves the celebrity problem using a stack-based algorithm.
5+ *
6+ * <p>Celebrity is someone known by everyone but doesn't know anyone else.
7+ * <p>Applications: Graph theory and social network analysis.
8+ *
9+ * @author Hardvan
10+ */
11+ public final class CelebrityFinder {
12+ private CelebrityFinder () {
13+ }
14+
15+ /**
16+ * Finds the celebrity in the given party matrix.
17+ *
18+ * @param party A 2D matrix where party[i][j] is 1 if i knows j, otherwise 0.
19+ * @return The index of the celebrity, or -1 if there is no celebrity.
20+ */
21+ public static int findCelebrity (int [][] party ) {
22+ int n = party .length ;
23+ int candidate = 0 ;
24+
25+ // Find a potential celebrity
26+ for (int i = 1 ; i < n ; i ++) {
27+ if (party [candidate ][i ] == 1 ) {
28+ candidate = i ;
29+ }
30+ }
31+
32+ // Verify the candidate
33+ for (int i = 0 ; i < n ; i ++) {
34+ if (i != candidate && (party [candidate ][i ] == 1 || party [i ][candidate ] == 0 )) {
35+ return -1 ;
36+ }
37+ }
38+ return candidate ;
39+ }
40+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .stacks ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ import org .junit .jupiter .api .Test ;
6+
7+ public class CelebrityFinderTest {
8+
9+ @ Test
10+ public void testCelebrityExists () {
11+ int [][] party = {
12+ {0 , 1 , 1 },
13+ {0 , 0 , 1 },
14+ {0 , 0 , 0 }
15+ };
16+ assertEquals (2 , CelebrityFinder .findCelebrity (party ));
17+ }
18+
19+ @ Test
20+ public void testNoCelebrity () {
21+ int [][] party = {
22+ {0 , 1 , 0 },
23+ {1 , 0 , 1 },
24+ {1 , 1 , 0 }
25+ };
26+ assertEquals (-1 , CelebrityFinder .findCelebrity (party ));
27+ }
28+ }
You can’t perform that action at this time.
0 commit comments