풀이
# DFS
def dfs(grap, v, visit):
# 지금 들린곳 체크
visit[v] = True
# 들린곳 순서에 따라 프린트
DFS.append(v)
# 작은 것부터 우선해서 들여
for i in sorted(grap[v]):
# 안 들렸다면 들려
if not visit[i]:
dfs(grap, i, visited)
# BFS
from collections import deque
def bfs(grap, v, visit):
# 덱처리
queue = deque([v])
# 방문 체크
visit[v] = True
while queue:
# 리스트에 맨 앞쪽 체크, 제거
n = queue.popleft()
# 체크한 부분 순서에따라 프린트
BFS.append(n)
# 체크된 리스트에 있는 숫자 꺼내기
for i in sorted(grap[n]):
# 안들렸음 다 넣어
if not visit[i]:
visit[i] = True
queue.append(i)
N, M, V = map(int, input().split())
graph = [[] for _ in range(N + 1)]
# 방문을 저장할 리스트
visited = [[] for _ in range(N + 1)]
visited_2 = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
DFS = []
BFS = []
dfs(graph, V, visited)
bfs(graph, V, visited_2)
print(*DFS)
print(*BFS)