File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import (
2+ List ,
3+ )
4+
5+ class Solution :
6+ """
7+ @param n: the number of vertices
8+ @param edges: the edges of undirected graph
9+ @return: the number of connected components
10+ """
11+ def count_components (self , n : int , edges : List [List [int ]]) -> int :
12+
13+ # DFS
14+ # ์๊ฐ ๋ณต์ก๋ O(n + e), ๊ณต๊ฐ๋ณต์ก๋ O(n + e) // n=๋
ธ๋์, e=๊ฐ์ ์
15+ # ์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์์ผ๋ก ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ ์์ฑ
16+ graph = [[] for _ in range (n )]
17+ for i , j in edges :
18+ graph [i ].append (j )
19+ graph [j ].append (i )
20+
21+ visited = set () # ๋ฐฉ๋ฌธํ ๋
ธ๋ ์ ์ฅํ ์งํฉ
22+ answer = 0 # ์ฐ๊ฒฐ ์์ ๊ฐ์
23+
24+ # ํ์ฌ node์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋
ธ๋ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌํ๋ ํจ์
25+ def dfs (node ):
26+ # ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ผ๋ฉด dfs ์ข
๋ฃ
27+ if node in visited :
28+ return
29+ visited .add (node ) # node ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
30+ # ์ฐ๊ฒฐ๋ ๋
ธ๋๋ค๋ ํ์
31+ for i in graph [node ]:
32+ dfs (i )
33+
34+ # ๋ชจ๋ ๋
ธ๋ ํ์ ํ ์ฐ๊ฒฐ ์์ ๊ฐ์ ์ธ๊ธฐ
35+ for i in range (n ):
36+ # ๋ฐฉ๋ฌธํ์ง ์์ ๋
ธ๋๋ผ๋ฉด dfs ํ์ํ๊ณ ์ฐ๊ฒฐ์์(answer) +1
37+ if i not in visited :
38+ dfs (i )
39+ answer += 1
40+
41+ return answer
You canโt perform that action at this time.
0 commit comments