[BaekJoon] λ°±μ€ 1260λ² : DFSμ BFS
Updated:
1260λ² : DFSμ BFS
μ΄μ [BaekJoon] 1620λ² : λλμΌ ν¬μΌλͺ¬ λ§μ€ν° μ΄λ€μ μ΄ λ¬Έμ λ₯Ό νκΈ° μ DFS, BFS νμ© νλ λ¬Έμ λ₯Ό νμλλ°
μκ°μ΄ λ무 μ€λκ±Έλ € νμ§ λͺ»νλ€. μμ μ BFS, DFS κ°λ μ μ 리ν μ μ΄ μμλλ° μνλ €μ λ νλ¬λ€..
κ·Έλμ μ€λ μ νν νκΈ° μν΄ BFS, DFS λ¬Έμ λ₯Ό νμλ€. C λ‘ κ΅¬νν λ λ³΄λ€ λ무λ무 κ°λ¨ν΄μ μ λ§ μ’μλ€..
κ·Έλνλ μ¬μ μΌλ‘ λ§λ€κ³ BFS λ νλ₯Ό, DFS λ μ€νμ μ¬μ©νλ©΄ ꡬν ν μ μλ€.
λ¬Έμ μμ μ μ μ΄ μ¬λ¬ κ° μΈ κ²½μ° μ μ λ²νΈκ° μμ κ²μ λ¨Όμ λ°©λ¬ΈνκΈ° λλ¬Έμ κ°μ μ 보λ₯Ό λͺ¨λ μ λ ₯ λ°μ ν
λ§μ§λ§μ μ λ ¬μ ν λ² μ© ν΄μ£Όλ©΄ μ μ λ²νΈκ° μμ μμλλ‘ λ°©λ¬Έ ν μ μλ€.
λ°©λ¬Έ νλ μ μ μ κ΄λ¦¬νλ κ²λ μ¬μ μΌλ‘ λ§λ€μλλ° in λͺ λ Ήμ μνν λ μ‘°κΈμ΄λΌλ μκ°μ μ€μ΄κΈ° μν¨μ΄λ€.
import sys
from collections import deque
def DFS(graph, start):
visit = dict()
stack = [start]
while stack:
visit_ver = stack.pop()
if visit_ver not in visit:
print(visit_ver, end=' ')
visit[visit_ver] = 1
for ver in reversed(graph[visit_ver]):
if ver not in visit:
stack.append(ver)
def BFS(graph, start):
visit = dict()
queue = deque([start])
while queue:
visit_ver = queue.popleft()
if visit_ver not in visit:
print(visit_ver, end=' ')
visit[visit_ver] = 1
for ver in graph[visit_ver]:
if ver not in visit:
queue.append(ver)
N, M, V = map(int, sys.stdin.readline().rsplit())
graph = {i: [] for i in range(1, N + 1)}
for _ in range(M):
start, end = map(int, sys.stdin.readline().rsplit())
graph[start].append(end)
graph[end].append(start)
for i in range(1, N + 1): # μ μ λ²νΈκ° μμ μμΌλ‘ λ°©λ¬Έν΄μΌνκΈ° λλ¬Έμ μ λ ¬νλ€
graph[i].sort()
DFS(graph, V)
print()
BFS(graph, V)
Leave a comment