1260: DFS와 BFS

ewillwin·2023년 5월 6일
0

Problem Solving (BOJ)

목록 보기
46/230

import sys
from collections import deque

tmp = list(map(int, sys.stdin.readline()[:-1].split(' ')))
N = tmp[0]; M = tmp[1]; V = tmp[2]
adjacent = [[] for _ in range(N+1)]
for _ in range(M):
    t0, t1 = map(int, sys.stdin.readline()[:-1].split(' '))
    adjacent[t0].append(t1)
    adjacent[t1].append(t0)

for _ in range(len(adjacent)):
    adjacent[_].sort()

visit_d = [False] * (N+1)
def dfs(start):
    visit_d[start] = True
    print(start, end=" ")
    for i in range(len(adjacent[start])):
        if not visit_d[adjacent[start][i]]:
            dfs(adjacent[start][i])

visit_b = [False] * (N+1)
def bfs(start):
    visit_b[start] = True
    nodes = deque([start])
    while nodes:
        v = nodes.popleft()
        print(v, end=" ")
        for i in range(len(adjacent[v])):
            if not visit_b[adjacent[v][i]]:
                visit_b[adjacent[v][i]] = True
                nodes.append(adjacent[v][i])

dfs(V)
print()
bfs(V)
  • bfs는 queue 자료구조를 사용함 (시간복잡도를 고려하여 deque 객체 사용)
  • adjacent list에서 first in first out 으로 인접한 node들을 먼저 탐색해줌
profile
💼 Software Engineer @ LG Electronics | 🎓 SungKyunKwan Univ. CSE

0개의 댓글