Skip to content

Commit 39c7473

Browse files
committed
[BOJ] #11724.연결요소의 개수 / 실버2 / 45(∆)
1 parent 3e7710d commit 39c7473

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from collections import defaultdict, deque
2+
import sys
3+
input = sys.stdin.readline
4+
5+
N, M = map(int, input().split()) # 정점의 개수, 간선의 개수
6+
graph = [[] for _ in range(N + 1)]
7+
for _ in range(M):
8+
u, v = map(int, input().split())
9+
graph[u].append(v)
10+
graph[v].append(u)
11+
12+
# 방문 여부 리스트 초기화
13+
visited = [False] * (N + 1)
14+
15+
# 연결 요소 개수
16+
connected_components = 0
17+
18+
def bfs(graph, start):
19+
queue = deque([start]) # 시작 정점을 큐에 추가
20+
visited[start] = True # 시작 정점을 방문 처리
21+
while queue:
22+
current = queue.popleft() # 큐에서 정점 꺼내기
23+
for neighbor in graph[current]: # 현재 정점의 모든 이웃에 대해 반복
24+
if not visited[neighbor]: # 방문하지 않은 경우만 처리
25+
visited[neighbor] = True # 방문 처리
26+
queue.append(neighbor) # 큐에 추가
27+
28+
for i in range(1, N+1):
29+
if not visited[i]: # 방문하지 않은 정점에서 BFS 수행
30+
bfs(graph, i)
31+
connected_components += 1
32+
33+
print(connected_components)

0 commit comments

Comments
 (0)