본문 바로가기
카테고리 없음

[백준/Python] 1260 DFS와 BFS - 작은 숫자 먼저 출력하기

by 뽀짜꼬 2025. 3. 28.
728x90
반응형

분명 맞는데 왜 틀렸지 왜 틀렸지 하면서 4시간 내내 고민 했는데..

리스트로 출력해서 그런거였다.

하..

(도움 준 스터디원님께 감사를..)

 

다음부턴 출력 형태를 꼬옥 잘 보리다..

DFS는 역순으로(내림차순), BFS는 오름차순으로 정렬해야 작은 숫자부터 나온다.

파이썬

# 정점 개수 N, 간선 개수 M, 탐색 시작 번호 V
N, M, V = map(int, input().split())

edgeList = []
graph = [[] for vertex in range(N+1)]

for i in range(M):
    e0, e1 = map(int, input().split())
    edgeList.append((e0, e1))

# 연결 그래프 만들기..
for edge in edgeList:
    graph[edge[0]].append(edge[1])
    graph[edge[1]].append(edge[0])

#DFS
def DFS(graph, V) :
    for i in range(len(graph)):
        graph[i].sort(reverse=True)
    visited = []
    stack = [V]

    while stack :
        current = stack.pop()

        if current in visited:  # 이미 방문한 노드 무시
            continue

        for n in graph[current]:
            if not n in visited:
                stack.append(n)
        visited.append(current)
    return ' '.join(map(str,visited))

print(DFS(graph, V))

#BFS
def BFS(graph, V):
    for i in range(len(graph)):
        graph[i].sort()

    visited = []
    queue = [V]

    while queue:
        current = queue.pop()
        
        if not current in visited:
            for n in graph[current]:
                if not n in visited:
                    queue.insert(0, n)
            visited.append(current)
    return ' '.join(map(str,visited))

print(BFS(graph, V))

 

728x90
반응형