728x90
반응형
기본적인 DFS & BFS 문제이다.
DFS 풀이
import sys
sys.setrecursionlimit(10000)
def dfs(node):
check[node] = 1
for n in graph[node]:
if check[n] == 0:
dfs(n)
N, M = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, sys.stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
check = [0]*(N+1)
cnt = 0
for i in range(1, N+1):
if check[i] == 0:
dfs(i)
cnt += 1
print(cnt)
BFS 풀이
import sys
from collections import deque
def bfs(node):
queue = deque()
queue.append(node)
while queue:
node = queue.popleft()
for n in graph[node]:
if check[n] == 0:
check[n] = 1
queue.append(n)
N, M = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, sys.stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
check = [0]*(N+1)
cnt = 0
for i in range(1, N+1):
if check[i] == 0:
check[i] = 1
bfs(i)
cnt += 1
print(cnt)
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 11725번 트리의 부모 찾기(python) (0) | 2021.03.11 |
---|---|
백준 알고리즘 10026번 적록색약(python) (0) | 2021.03.11 |
백준 알고리즘 1302번 베스트셀러(python) (0) | 2021.03.11 |
백준 알고리즘 11557번 Yangjojang of The Year(python) (0) | 2021.03.11 |
백준 알고리즘 4963번 섬의 개수(python) (0) | 2021.03.10 |