#백준 11724번
#DFS 함수 정의
def dfs(vertex:int, neighbor:dict, visited:dict) -> int:
#base case : 방문한 정점일 경우 함수 종료 및 0 반환
if visited[vertex]:
return 0
#방문한 적이 없는 정점일 경우 탐색 시작
else:
#정점 방문처리
visited[vertex] = True
#정점과 이웃한 정점을 순회하며 dfs 함수 호출
for i in neighbor[vertex]:
dfs(i, neighbor, visited)
return 1
#정점의 개수 및 간선의 개수 받기
vertex_num, edge_num = map(int, input().split())
#정점 별 이웃한 정점 목록 딕셔너리, 정점 방문 여부 딕셔너리 초기화
neighbor = dict()
visited = dict()
for i in range(1, vertex_num+1):
neighbor[i] = []
visited[i] = False
#간선 양 끝점 받아 neighbor에 저장
for _ in range(edge_num):
u, v = map(int, input().split())
neighbor[u].append(v)
neighbor[v].append(u)
#모든 정점을 순회하며 연결 요소 개수 구하기
connected_component_num = 0
for vertex in range(1, vertex_num+1):
connected_component_num += dfs(vertex, neighbor, visited)
#결과 출력
print(connected_component_num)
#백준 11724번
import sys
sys.setrecursionlimit(10**6)
#DFS 함수 정의
def dfs(vertex:int, neighbor:dict, visited:dict) -> int:
#base case : 방문한 정점일 경우 함수 종료 및 0 반환
if visited[vertex]:
return 0
#방문한 적이 없는 정점일 경우 탐색 시작
else:
#정점 방문처리
visited[vertex] = True
#정점과 이웃한 정점을 순회하며 dfs 함수 호출
for i in neighbor[vertex]:
dfs(i, neighbor, visited)
return 1
#정점의 개수 및 간선의 개수 받기
vertex_num, edge_num = map(int, input().split())
#정점 별 이웃한 정점 목록 딕셔너리, 정점 방문 여부 딕셔너리 초기화
neighbor = dict()
visited = dict()
for i in range(1, vertex_num+1):
neighbor[i] = []
visited[i] = False
#간선 양 끝점 받아 neighbor에 저장
for _ in range(edge_num):
u, v = map(int, input().split())
neighbor[u].append(v)
neighbor[v].append(u)
#모든 정점을 순회하며 연결 요소 개수 구하기
connected_component_num = 0
for vertex in range(1, vertex_num+1):
connected_component_num += dfs(vertex, neighbor, visited)
#결과 출력
print(connected_component_num)
#백준 11724번
import sys
input = sys.stdin.readline
#get vertex_num, edge_num
vertex_num, edge_num = map(int, input().split())
#create node_list
node_list = [i for i in range(0, vertex_num+1)]
#get edge information, change latter node's value to former node if they are connected
for _ in range(edge_num):
u, v = map(int, input().split())
if node_list[u] != node_list[v]:
val = node_list[v]
for index, node in enumerate(node_list):
if node == val:
node_list[index] = node_list[u]
#delete duplicate value by change list into set
node_set = set(node_list)
#print answer
print(len(node_set)-1)
언어를 Python3로 설정하느냐 PyPy3로 설정하느냐에 따라 메모리 소모 및 시간 소요 정도가 달라진다는 것도 확인했다.