The Celebrity Problem | Max ; Person with 2 is celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) ; The graph needs not be constructed as the edges can be found by using knows function degree array ; ; Query for all edges ; Set the degrees ; Find a person with indegree n - 1 and out degree 0 ; Driver code
N = 8 NEW_LINE MATRIX = [ [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] ] NEW_LINE def knows ( a , b ) : NEW_LINE INDENT return MATRIX [ a ] [ b ] NEW_LINE DEDENT def findCelebrity ( n ) : NEW_LINE INDENT indegree = [ 0 for x in range ( n ) ] NEW_LINE outdegree = [ 0 for x in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT x = knows ( i , j ) NEW_LINE outdegree [ i ] += x NEW_LINE indegree [ j ] += x NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( indegree [ i ] == n - 1 and outdegree [ i ] == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE id_ = findCelebrity ( n ) NEW_LINE if id_ == - 1 : NEW_LINE INDENT print ( " No ▁ celebrity " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Celebrity ▁ ID " , id_ ) NEW_LINE DEDENT DEDENT