[LeetCode] 1791. Find Center of Star Graph

원숭2·2022년 1월 25일
0

LeetCode

목록 보기
15/51

문제

풀이

  1. edge의 갯수를 구하기 위해 count dictionary 만듦.
  2. for문을 돌며 각 vertex마다 연결된 edge갯수 세어 줌.
  3. graph의 중앙은 모두와 연결되어있기 때문에 edge의 갯수와 같으므로 해당 값 return.

코드

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        count = dict()
        
        for i in range(len(edges)) :
            if edges[i][0] not in count :
                count[edges[i][0]] = 1
            else :
                count[edges[i][0]] += 1
            
            if edges[i][1] not in count :
                count[edges[i][1]] = 1
            else :
                count[edges[i][1]] += 1
        
        for c in list(count.keys()) :
            if count[c] == len(edges) :
                return c

0개의 댓글