728x90
반응형

기본적인 DFS & BFS 문제이다. 

from collections import deque

def dfs(node):
    if check[node] == 0:
        print(node, end=' ')
        check[node] = 1
        for n in sorted(li[node]):
            dfs(n)

def bfs(start):
    queue = deque([start])
    while queue:
        node = queue.popleft()
        print(node, end=' ')
        check[node] = 1
        for n in sorted(li[node]):
            if check[n] == 0:
                queue.append(n)
                check[n] = 1 

N, M, V = map(int, input().split())
li = [[] for _ in range(N+1)]
for _ in range(M):
    a, b = map(int, input().split())
    li[a].append(b)
    li[b].append(a)
check = [0]*(N+1)
dfs(V)
print()
check = [0]*(N+1)
bfs(V)
728x90
반응형

+ Recent posts