[코테 스터디 24일차 TIL] Find Center of Star Graph

dev_jubby·2024년 8월 14일
1

코테스터디

목록 보기
24/36



💛 오늘의 학습 키워드

[그래프] Find Center of Star Graph



📝 문제

문제 설명

There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.

You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.

제한 조건

  • 3 <= n <= 10510^5
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= ui, vi <= n
  • ui != vi
  • The given edges represent a valid star graph.

입출력 예

Example 1

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.


Example 2

Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1



💬 내 풀이

class Solution {
    public int findCenter(int[][] edges) {
        if(edges[0][0] == edges[1][0]) {
           return edges[0][0];
        }else if(edges[0][0] == edges[1][1]) {
           return edges[0][0];
        }else {
           return edges[0][1];
        }
    }
}

💻 내 접근 방법

  1. 모든 배열안에는 center node 가 존재하기 때문에, 굳이 모든 케이스를 보지 않고, 앞에 두개만 비교해도 답을 도출해낼 수 있을 것 같았다.
  2. [0][0] 인덱스가 [1][0] 과 같으면 해당 값을 return 하고, [0][0] 인덱스가 [1][1] 과 같으면 해당 값을 return 하고, 이외에는 center node 가 [0][1] 에 있는 값이므로 해당 값을 return 해주었다.



💦 회고

처음에는 for문으로 모든 케이스를 비교해보려 했는데, 이중 배열이기 때문에 그럴 필요가 없다는 것을 중간에 깨달았다!




profile
신입 개발자 쥬비의 기술 블로그 입니다.

0개의 댓글