Skip to content

Commit 12b0db2

Browse files
committed
number-of-connected-components-in-an-undirected-graph solution
1 parent c20cebb commit 12b0db2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

0 commit comments

Comments
ย (0)