본문 바로가기
Algorithm/BFS, DFS

[백준] 1260번 DFS와 BFS

by 등촌동 꼬북이 2020. 9. 4.

DFS와 BFS 기초

 

from collections import deque

def DFS(graph, V):
    visited = []
    tempStack = [V]
    while tempStack:
        node = tempStack.pop()
        if node not in visited:
            visited.append(node)
            tempStack.extend(sorted(graph[node], reverse=True))
    return visited

def BFS(graph, V):
    visited = []
    queue = deque([V])
    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.append(node)
            queue.extend(sorted(graph[node]))
    return visited

N, M, V = map(int, input().split())
graph = [set([]) for i in range(N + 1)]

for i in range(M):
    a, b = map(int, input().split())
    graph[a].add(b)
    graph[b].add(a)
    
print(*DFS(graph, V))
print(*BFS(graph, V))

댓글