-
Notifications
You must be signed in to change notification settings - Fork 72
/
Celebrity_Problem.java
86 lines (83 loc) · 1.67 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.*;
class Celebrity_Problem
{
int top=-1,topi=-1;
int max=1000;
int[] stack= new int[1000];
int[][] Ar;
void push(int x)
{
if(top==(max-1))
{
System.out.println("Stack Overflow");
}
else
{
stack[++top]=x;
}
}
int pop()
{
int elem=stack[top--];
return elem;
}
int assume()
{
return(stack[top]);
}
void main()
{
Scanner sc = new Scanner(System.in);
Celebrity_Problem obj= new Celebrity_Problem();
int i,j,topi=-1;
int n=sc.nextInt();
int[][] Ar=new int[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
Ar[i][j]=sc.nextInt();
}
}
for(i=0;i<n;i++)
{
obj.push(i);
}
for(i=0;i<(n-1);i++)
{
int ele1 = obj.pop();
int ele2 = obj.pop();
if(Ar[ele1][ele2]==0)
{
obj.push(ele1);
}
else if(Ar[ele1][ele2]==1)
{
obj.push(ele2);
}
}
int assumed= obj.assume();
int found=1;
for (i=0;i<n;i++)
{
if(Ar[assumed][i]!=0)
{
found=0;
break;
}
if(i!=assumed && Ar[i][assumed]!=1)
{
found=0;
break;
}
}
if(found==0)
{
System.out.println("-1");
}
else
{
System.out.println(assumed);
}
}
}