File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments