문제풀이/일일연습문제
[Graph]99클럽 코테 스터디 22일차 TIL + 1916-find-center-of-star-graph
Mo_bi!e
2024. 8. 15. 13:45
1916. Find Center of Star Graph
Easy
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.
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
Constraints:
3 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
- The given
edges
represent a valid star graph.
<내코드>
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
common_value = set(edges[0])
for edge in edges[1:]:
common_value = common_value.intersection(set(edge))
print(common_value)
return common_value.pop()
- 모든 list의 공통 노드가 무엇인지 찾기위해 집중함
=> 하나씩 if문으로 구현하는 방법도있지만, set 으로 변경 후 intersecion 으로 구현함
<모범사례>
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
# 첫 두 엣지에서 공통 노드를 찾음
if edges[0][0] == edges[1][0] or edges[0][0] == edges[1][1]:
return edges[0][0]
else:
return edges[0][1]
- 아무리 엣지의 수가 많다고 하더라도, 문제의 조건은 모두 예외가 없기 때문에
=> 첫 두개의 엣지만 집중하면 충분히 가능함
- 스타그래프의 특성에 집중하자
=> 처음 두개의 엣지의 공통된 노드만 찾으면 됨
<보충학습>
- 실무에서의 활용
=> 네트워크 중심성 분석하기