277. Find the Celebrity
Problem
Given n people and an adjacency matrix of who knows whom, find the celebrity, or return -1 when none exists.
There are n people labeled 0 to n-1 at a party. You are given an n x n matrix where matrix[a][b] is 1 when person a knows person b, and 0 otherwise. The diagonal entries are always 0 because nobody is treated as knowing themselves.
A celebrity is a person c such that:
- Every other person knows
c:matrix[j][c] == 1for allj != c. cknows nobody else:matrix[c][j] == 0for allj != c.
Return the label of the celebrity. If no such person exists, return -1. At most one celebrity can exist.
Examples
Input: [1,[[0]]]
Output: 0
Input: [2,[[0,0],[1,0]]]
Output: 0
Hints
A person who knows someone cannot be the celebrity, and a person whom someone does not know cannot be the celebrity.
Eliminate candidates in a single pass by moving the candidate to the other person whenever the current candidate fails.
Verify the surviving candidate against every other person before returning the label.
Related Problems
277. Find the Celebrity
Given `n` people and an adjacency matrix of who knows whom, find the celebrity, or return `-1` when none exists.