๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 1260 - DFS์™€ BFS

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 1260๋ฒˆ

ํ’€์ด ๊ณผ์ •

DFS ์™€ BFS ์—ฐ์‚ฐ์„ ๊ตฌํ˜„ํ•˜๋Š” ๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋จผ์ € ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์€ ๊ฐ„์„  ์ •๋ณด๋กœ ๊ทธ๋ž˜ํ”„๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ดํ›„ DFS ์™€ BFS ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque

sys.setrecursionlimit(10 ** 6)


def bfs(graph, start):
    q = deque()
    visit = [0] * (N + 1)
    order = []

    q.append(start)
    visit[start] = 1

    while q:
        here = q.popleft()
        order.append(here)

        for there in sorted(graph[here]):
            if not visit[there]:
                visit[there] = 1
                q.append(there)

    return order


def dfs(graph, here, visit, result):
    visit[here] = 1
    result.append(here)

    for there in sorted(graph[here]):
        if not visit[there]:
            dfs(graph, there, visit, result)


def make_graph():
    graph = [[] for _ in range(N + 1)]

    for frm, to in edges:
        graph[frm].append(to)
        graph[to].append(frm)

    return graph


def solution():
    graph = make_graph()

    dfs_visit = [0] * (N + 1)
    dfs_result = []
    dfs(graph, V, dfs_visit, dfs_result)
    print(*dfs_result)

    bfs_result = bfs(graph, V)
    print(*bfs_result)


if __name__ == '__main__':
    N, M, V = list(map(int, sys.stdin.readline().split()))
    edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

    solution()
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 17626 - Four Squares  (0) 2021.03.18
BOJ 1303 - ์ „์Ÿ - ์ „ํˆฌ  (0) 2021.03.18
BOJ 6550 - ๋ถ€๋ถ„ ๋ฌธ์ž์—ด  (0) 2021.03.18
BOJ 10819 - ์ฐจ์ด๋ฅผ ์ตœ๋Œ€๋กœ  (0) 2021.03.18
BOJ 15240 - Paint bucket  (0) 2021.03.18

๐Ÿ’ฌ ๋Œ“๊ธ€