Skip to content

Commit 4824991

Browse files
committed
graph-valid-tree solution (py)
1 parent c5bf746 commit 4824991

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
- ์ •์  ๊ฐœ์ˆ˜ n, ๊ฐ„์„  ๋ฐฐ์—ด edges
3+
- ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„
4+
5+
ํŠธ๋ฆฌ ์กฐ๊ฑด
6+
1. ์™„์ „ํžˆ ์—ฐ๊ฒฐ๋œ ๊ทธ๋ž˜ํ”„์—ฌ์•ผ ํ•จ -> ์ „์ฒด ํƒ์ƒ‰ ๊ฐ€๋Šฅ
7+
2. ๊ทธ๋ž˜ํ”„์— ์ˆœํ™˜ํ•˜๋Š” ๋ถ€๋ถ„์ด ์—†์–ด์•ผ ํ•จ
8+
9+
ํŠธ๋ฆฌ ํŠน์„ฑ์ƒ ํ•ญ์ƒ e = n - 1, ์ฆ‰ ๊ฐ„์„ ์˜ ์ˆ˜ = ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ - 1
10+
11+
TC: O(n)
12+
SC: O(n)
13+
"""
14+
15+
from typing import List
16+
17+
class Solution:
18+
def validTree(self, n: int, edges: List[List[int]]) -> bool:
19+
graph = [[] for _ in range(n)]
20+
visited = set()
21+
22+
for a, b in edges:
23+
graph[a].append(b)
24+
graph[b].append(a)
25+
26+
def has_cycle(node, prev):
27+
# ์ด๋ฏธ ๋ฐฉ๋ฌธ = ์ˆœํ™˜ -> ํŠธ๋ฆฌ x
28+
if node in visited:
29+
return True
30+
visited.add(node)
31+
for adj in graph[node]:
32+
if adj == prev:
33+
continue
34+
if has_cycle(adj, node):
35+
return True
36+
37+
return False
38+
39+
if has_cycle(0, -1):
40+
return False
41+
42+
return len(visited) == n

0 commit comments

Comments
ย (0)