반응형
https://www.acmicpc.net/problem/11724
import collections
n, m = map(int, input().split())
graph = collections.defaultdict(list)
for i in range(m):
u,v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
discovered = []
count = 0
def dfs(node):
discovered.append(node)
lst = graph[node]
for i in range(len(lst)):
next = lst[i]
if next not in discovered:
dfs(next)
for i in range(1,n+1):
if i not in discovered:
count += 1
dfs(i)
print(count)
아주 기본적인 dfs 문제다.
나는 재귀구조를 쓸 때 보통 중단 조건을 만들기 때문에 아래 코드가 좀 더 익숙한 거 같다.
import collections
n, m = map(int, input().split())
graph = collections.defaultdict(list)
for i in range(m):
u,v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
discovered = []
count = 0
def dfs(node):
if node in discovered:
return
discovered.append(node)
lst = graph[node]
for i in range(len(lst)):
next = lst[i]
dfs(next)
for i in range(1,n+1):
if i not in discovered:
count += 1
dfs(i)
print(count)
댓글