커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
백준 DFS, BFS
실무에 바로 쓰이는 알고리즘 by Python
0주차
북마크
정*영
댓글
1
추천
0
조회수
4
조회수
4
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


출력 초과가 뜨는데 어떻게 해결해야할지 모르겠습니다.

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)



취소
 공유
취소
댓글 0
댓글 알림
나의얼굴