-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCelebrity_Problem.java
More file actions
62 lines (50 loc) · 1.2 KB
/
Celebrity_Problem.java
File metadata and controls
62 lines (50 loc) · 1.2 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
// Java program to find celebrity
import java.util.*;
class Celebrity_Problem {
// Max # of persons in the party
//static final int N = 8;
// Person with 2 is celebrity
static int MATRIX[][] = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
static int knows(int a, int b) { return MATRIX[a][b]; }
// Returns -1 if celebrity is not present.
// If present, returns id (value from 0 to n-1).
static int findCelebrity(int n)
{
// the graph needs not be constructed
// as the edges can be found by
// using knows function
// degree array;
int[] colsum = new int[n];
int[] rowsum = new int[n];
// query for all edges
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int x = knows(i, j);
// set the degrees
rowsum[i] += x;
colsum[j] += x;
}
}
// find a person with indegree n-1
// and out degree 0
for (int i = 0; i < n; i++)
if (colsum[i] == n - 1 && rowsum[i] == 0)
return i;
return -1;
}
// Driver code
public static void main(String[] args)
{
int n = 4;
int id = findCelebrity(n);
if (id == -1)
System.out.print("No celebrity");
else
System.out.print("Celebrity ID " + id);
}
}