forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlylaminju.py
More file actions
45 lines (34 loc) ยท 1.33 KB
/
lylaminju.py
File metadata and controls
45 lines (34 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
'''
๋
ธ๋์ ๊ฐ์๋ฅผ n, ๊ฐ์ ์ ๊ฐ์๋ฅผ e ๋ผ๊ณ ํ ๋,
์๊ฐ ๋ณต์ก๋: O(n + e)
- ๊ทธ๋ํ์ ๋ชจ๋ ๋
ธ๋์ ๊ฐ์ ์ ๋ฐฉ๋ฌธํ๋ฏ๋ก O(n + e)
๊ณต๊ฐ ๋ณต์ก๋: O(n + e)
- ์ธ์ ๋ฆฌ์คํธ์ ๋ฐฉ๋ฌธ ๋ฐฐ์ด์ ์ ์ฅํ๋ ๋ฐ O(n + e)์ ๊ณต๊ฐ์ด ํ์ํฉ๋๋ค.
'''
from typing import List
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
graph = { i: [] for i in range(n) }
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = set()
def hasCycle(node, parent):
if node in visited:
return True
visited.add(node)
for neighbor in graph[node]:
if neighbor == parent:
continue # ๋ถ๋ชจ ๋
ธ๋๋ก ๋์๊ฐ์ง ์๊ธฐ
if hasCycle(neighbor, node):
return True
return False
# 0๋ฒ ๋
ธ๋์์ DFS ์์
if hasCycle(0, -1):
return False
# ๋ชจ๋ ๋
ธ๋๊ฐ ๋ฐฉ๋ฌธ๋์๋์ง ํ์ธ (์ฐ๊ฒฐ์ฑ ์ฒดํฌ)
return len(visited) == n
# Example
solution = Solution()
print(solution.validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]])) # Output: True
print(solution.validTree(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]])) # Output: False