File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+
4+ class Solution :
5+ def validTree (self , n : int , edges : List [List [int ]]) -> bool :
6+ """
7+ - Idea: ์ ํจํ ํธ๋ฆฌ๋ผ๋ฉด ๋ง์กฑํด์ผ ํ๋ ์กฐ๊ฑด๋ค์ ํ์ฉํ์ฌ ํธ๋ฆฌ ์ฌ๋ถ๋ฅผ ํ๋จํ๋ค.
8+ - Time Complexity: O(v + e). v์ e๋ ๊ฐ๊ฐ ๋
ธ๋์ ์, ์ฐ๊ฒฐ๋ ์ (์ฃ์ง)์ ์
9+ ์ธ์ ๋ฆฌ์คํธ๋ก ๋ง๋ ๊ทธ๋ํ๋ฅผ ์ํํ ๋, ๋
ธ๋๋ง๋ค ์ฐ๊ฒฐ๋ ์ฃ์ง๋ฅผ ๋ฐ๋ผ๊ฐ๋ฉฐ ํ์ํ๋ฏ๋ก O(v + e)์ด ์์๋๋ค.
10+ - Space Complexity: O(v + e). v์ e๋ ๊ฐ๊ฐ ๋
ธ๋์ ์, ์ฃ์ง์ ์
11+ ๊ทธ๋ํ๋ฅผ ์ธ์ ๋ฆฌ์คํธ๋ก ์ ์ฅํ๊ธฐ ์ํด O(v + e)์ ๊ณต๊ฐ์ด ํ์ํ๋ค.
12+
13+ """
14+ if len (edges ) != n - 1 :
15+ return False
16+
17+ graph = {i : [] for i in range (n )}
18+
19+ for v1 , v2 in edges :
20+ graph [v1 ].append (v2 )
21+ graph [v2 ].append (v1 )
22+
23+ visited = set ()
24+
25+ def DFS (v : int ) -> None :
26+ visited .add (v )
27+
28+ for adj in graph [v ]:
29+ if adj not in visited :
30+ DFS (adj )
31+
32+ DFS (0 )
33+
34+ return len (visited ) == n
You canโt perform that action at this time.
0 commit comments