백준 1260 : DFS와 BFS (파이썬)

Yibangwon·2022년 3월 5일
0

알고리즘 문제풀이

목록 보기
19/60


정답 코드

import sys
N, M, V = map(int, sys.stdin.readline().split())

gra = [[] for i in range(1001)]

for i in range(M):
    a, b = map(int, sys.stdin.readline().split())
    gra[a].append(b)
    gra[b].append(a)

for i in range(1, N + 1):
    gra[i].sort()

def dfs(start):
    visited[start] = True
    print(start, end=' ')
    
    for dst in gra[start]:
        if not visited[dst]:
            dfs(dst)

def bfs(start):
    q = []
    q.append(start)
    visited[start] = True

    while len(q) > 0:
        curr = q[0]
        print(curr, end=' ')
        del q[0]
        for dst in gra[curr]:
            if not visited[dst]:
                q.append(dst)
                visited[dst] = True

visited = [False for i in range(1001)]
dfs(V)
print()
visited = [False for i in range(1001)]
bfs(V)

문제 유형

DFS, BFS

profile
I Don’t Hope. Just Do.

0개의 댓글