백준 11724번 연결 요소의 개수

Solution

import sys

input = sys.stdin.readline
sys.setrecursionlimit(100000)

n, m = map(int, input().split())

graph = [[] for _ in range(n + 1)]

for _ in range(m):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

count = 0

visited = [False] * (n + 1)


def dfs(v):
    visited[v] = True
    for i in graph[v]:
        if not visited[i]:
            dfs(i)


for v in range(1, n + 1):
    if not visited[v]:
        dfs(v)
        count += 1
print(count)