---
# System prepended metadata

title: Leetcode 1791. Find center of star graph

---

# Leetcode 1791. Find center of star graph

## 記錄下無向圖的每個頂點度數

透過題目可以知道，連接的邊數目為 |V(E)| = |V(G)| - 1，且中心點的節點分支度(degree)為 |V(G)| - 1

而透過題目又可得知 **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.**

所以可以透過此條件計算出節點數為 edges + 1

計算出了節點數目後，就可以構造出紀錄每個節點分支度的陣列，最後確認分之度為 |V(E)|，的節點即為中心節點

```python=
class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        degree = [0] * (len(edges) + 1)
        for i in range(len(edges)):
            degree[edges[i][0] - 1] += 1
            degree[edges[i][1] - 1] += 1
        for i in range(len(degree)):
            if degree[i] == len(edges):
                return i + 1
        return -1
```

## 比對所有邊的交集

```python
class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        result = edges[0]
        for i in range(1, len(edges)):
            result = list(set(result) & set(edges[i]))
        return result.pop()

```
python 一行
```python=
class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        return (set(edges[0]) & set(edges[1])).pop()
```

