forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyyyyyyyyyKim.py
More file actions
46 lines (37 loc) ยท 1.33 KB
/
yyyyyyyyyKim.py
File metadata and controls
46 lines (37 loc) ยท 1.33 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
35
36
37
38
39
40
41
42
43
44
45
46
from typing import (
List,
)
class Solution:
"""
@param n: An integer
@param edges: a list of undirected edges
@return: true if it's a valid tree, or false
"""
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
# DFS(๊ทธ๋ํ ํ์)
# ์๊ฐ๋ณต์ก๋ O(n), ๊ณต๊ฐ๋ณต์ก๋ O(n)
# ํธ๋ฆฌ์ ๊ฐ์ ์๋ ํญ์ "๋
ธ๋ ์ -1"(์๋๋ฉด ๋ฐ๋ก False)
if len(edges) != n-1:
return False
# ์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์์ผ๋ก ๊ทธ๋ํ ์์ฑ
graph = [[] for _ in range(n)]
for i, j in edges:
graph[i].append(j)
graph[j].append(i)
# set์ฌ์ฉ(๋ฐฉ๋ฌธ์ฌ๋ถ๋ง ๋น ๋ฅด๊ฒ ํ์(in์ฐ์ฐ ์๊ฐ๋ณต์ก๋ O(1))
visited = set()
def dfs(node,prev):
# ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฉด ์ข
๋ฃ
if node in visited:
return
visited.add(node)
# ํ์ฌ ๋
ธ๋์ ์ด์ ํ์
for i in graph[node]:
# ๋ฐ๋ก ์ด์ ๋
ธ๋ ํจ์ค(๋ฌด๋ฐฉํฅ ๊ทธ๋ํ๋๊น)
if i == prev:
continue
dfs(i, node)
# 0๋ฒ ๋
ธ๋๋ถํฐ ํ์ ์์
dfs(0, -1)
# ๋ฐฉ๋ฌธํ ๋
ธ๋ ์์ ์ ์ฒด ๋
ธ๋ ์๊ฐ ๊ฐ์ผ๋ฉด ์ฐ๊ฒฐ ๊ทธ๋ํ -> ํธ๋ฆฌ
return len(visited) == n