forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathradiantchoi.py
More file actions
34 lines (25 loc) Β· 1.13 KB
/
radiantchoi.py
File metadata and controls
34 lines (25 loc) Β· 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from typing import List
# μ΄λ€ κ·Έλνκ° Valid Treeλ €λ©΄?
# μνμ΄ λ°μνμ§ μμΌλ©΄μ, λͺ¨λ λ
Έλκ° μ°κ²°λμ΄ μμ΄μΌ νλ€.
# nκ°μ λ
Έλλ₯Ό λͺ¨λ μ°κ²°νλ λ° νμν κ°μ μ κ°―μλ n - 1κ°
# μν λ°μ νμ§ -> Union Find
class Solution:
def find(self, parent: List[int], n: int) -> int:
if parent[n] == n:
return n
parent[n] = self.find(parent, parent[n])
return parent[n]
def union(self, parent: List[int], left: int, right: int) -> bool:
left_parent = self.find(parent, left)
right_parent = self.find(parent, right)
if left_parent == right_parent:
return False
parent[right_parent] = left_parent
return True
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
parents = list(range(n))
for edge in edges:
# Union Findμμ Falseκ° λ°νλλ€λ κ²μ μνμ΄ λ°μνλ€λ κ²
if not self.union(parents, edge[0], edge[1]):
return False
return len(edges) == n - 1