forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmangodm-web.py
More file actions
34 lines (24 loc) ยท 1.09 KB
/
mangodm-web.py
File metadata and controls
34 lines (24 loc) ยท 1.09 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
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
"""
- Idea: ์ ํจํ ํธ๋ฆฌ๋ผ๋ฉด ๋ง์กฑํด์ผ ํ๋ ์กฐ๊ฑด๋ค์ ํ์ฉํ์ฌ ํธ๋ฆฌ ์ฌ๋ถ๋ฅผ ํ๋จํ๋ค.
- Time Complexity: O(v + e). v์ e๋ ๊ฐ๊ฐ ๋
ธ๋์ ์, ์ฐ๊ฒฐ๋ ์ (์ฃ์ง)์ ์
์ธ์ ๋ฆฌ์คํธ๋ก ๋ง๋ ๊ทธ๋ํ๋ฅผ ์ํํ ๋, ๋
ธ๋๋ง๋ค ์ฐ๊ฒฐ๋ ์ฃ์ง๋ฅผ ๋ฐ๋ผ๊ฐ๋ฉฐ ํ์ํ๋ฏ๋ก O(v + e)์ด ์์๋๋ค.
- Space Complexity: O(v + e). v์ e๋ ๊ฐ๊ฐ ๋
ธ๋์ ์, ์ฃ์ง์ ์
๊ทธ๋ํ๋ฅผ ์ธ์ ๋ฆฌ์คํธ๋ก ์ ์ฅํ๊ธฐ ์ํด O(v + e)์ ๊ณต๊ฐ์ด ํ์ํ๋ค.
"""
if len(edges) != n - 1:
return False
graph = {i: [] for i in range(n)}
for v1, v2 in edges:
graph[v1].append(v2)
graph[v2].append(v1)
visited = set()
def DFS(v: int) -> None:
visited.add(v)
for adj in graph[v]:
if adj not in visited:
DFS(adj)
DFS(0)
return len(visited) == n