Leetcode - 1791. Find Center of Star Graph

숲사람·2022년 11월 9일
0

멘타트 훈련

목록 보기
182/237

문제

1부터 n번호를 가진 노드 n개로 이루어진 무방향 그래프가 주어진다. 모든 노드와 연결되는 하나의 center노드가 존재하는데 이 노드를 찾아라.

Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.

해결

class Solution {
public:
    int findCenter(vector<vector<int>>& edges) {
        int esize = edges.size() + 2;
        vector<vector<int>> graph(esize);
        for (auto it: edges) {
            graph[it[0]].push_back(it[1]);
            graph[it[1]].push_back(it[0]);
        }
        for (int i = 1; i < esize; i++) {
            if (graph[i].size() > 1)
                return i;
        }
        return 0;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글