
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
출력 초과가 뜨는데 어떻게 해결해야할지 모르겠습니다.
https://www.acmicpc.net/problem/1260
import sys
from collections import deque
def dfs(graph, cur_v, visited):
visited.append(cur_v)
print(cur_v, end = ' ')
for next_v in graph[cur_v]:
if next_v not in visited:
dfs(graph, next_v, visited)
def bfs(graph, start):
q = deque([start])
visited = []
while q:
cur_v = q.popleft()
visited.append(cur_v)
print(cur_v, end = ' ')
for next_v in graph[cur_v]:
if next_v not in visited:
q.append(next_v)
for i in visited:
print(i, end = ' ')
input = sys.stdin.readline
N, M, V = map(int, input().split())
graph = {i: [] for i in range(1, N+1)}
for _ in range(M):
n1, n2 = map(int, input().split())
graph[n1].append(n2)
graph[n2].append(n1)
# DFS 실행
visited = []
dfs(graph, V, visited)
for i in visited:
print(i, end = ' ')
print()
# BFS 실행
bfs(graph, V)
