Skip to content

Commit 85ab3a9

Browse files
committed
graph-valid-tree solution
1 parent 1f00216 commit 85ab3a9

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import (
2+
List,
3+
)
4+
5+
class Solution:
6+
"""
7+
@param n: An integer
8+
@param edges: a list of undirected edges
9+
@return: true if it's a valid tree, or false
10+
"""
11+
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
12+
# DFS(๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰)
13+
# ์‹œ๊ฐ„๋ณต์žก๋„ O(n), ๊ณต๊ฐ„๋ณต์žก๋„ O(n)
14+
15+
# ํŠธ๋ฆฌ์˜ ๊ฐ„์„  ์ˆ˜๋Š” ํ•ญ์ƒ "๋…ธ๋“œ ์ˆ˜ -1"(์•„๋‹ˆ๋ฉด ๋ฐ”๋กœ False)
16+
if len(edges) != n-1:
17+
return False
18+
19+
# ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ๋ฐฉ์‹์œผ๋กœ ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
20+
graph = [[] for _ in range(n)]
21+
for i, j in edges:
22+
graph[i].append(j)
23+
graph[j].append(i)
24+
25+
# set์‚ฌ์šฉ(๋ฐฉ๋ฌธ์—ฌ๋ถ€๋งŒ ๋น ๋ฅด๊ฒŒ ํƒ์ƒ‰(in์—ฐ์‚ฐ ์‹œ๊ฐ„๋ณต์žก๋„ O(1))
26+
visited = set()
27+
28+
def dfs(node,prev):
29+
# ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฉด ์ข…๋ฃŒ
30+
if node in visited:
31+
return
32+
visited.add(node)
33+
34+
# ํ˜„์žฌ ๋…ธ๋“œ์™€ ์ด์›ƒ ํƒ์ƒ‰
35+
for i in graph[node]:
36+
# ๋ฐ”๋กœ ์ด์ „ ๋…ธ๋“œ ํŒจ์Šค(๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋‹ˆ๊นŒ)
37+
if i == prev:
38+
continue
39+
dfs(i, node)
40+
41+
42+
# 0๋ฒˆ ๋…ธ๋“œ๋ถ€ํ„ฐ ํƒ์ƒ‰ ์‹œ์ž‘
43+
dfs(0, -1)
44+
45+
# ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ ์ˆ˜์™€ ์ „์ฒด ๋…ธ๋“œ ์ˆ˜๊ฐ€ ๊ฐ™์œผ๋ฉด ์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„ -> ํŠธ๋ฆฌ
46+
return len(visited) == n

0 commit comments

Comments
ย (0)