DonHurry

[Python] ๋ฐฑ์ค€ 1260๋ฒˆ - DFS์™€ BFS ๋ณธ๋ฌธ

Problem Solving

[Python] ๋ฐฑ์ค€ 1260๋ฒˆ - DFS์™€ BFS

_๋„๋… 2022. 11. 26. 01:40

๐Ÿ“– ๋ฌธ์ œ

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net

 

๐Ÿ”Ž ํ’€์ด

DFS์™€ BFS๋ฅผ ๊ตฌํ˜„ํ•ด๋ณด๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. DFS๋Š” ์Šคํƒ, BFS๋Š” ํ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค.

 

๐Ÿ’ป ์ฝ”๋“œ

import sys
import collections

input = sys.stdin.readline
graph = collections.defaultdict(list)
N, M, V = map(int, input().split())
for _ in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)


def dfs(v, discovered = []):
    discovered.append(v)
    for w in sorted(graph[v]):
        if w not in discovered:
            discovered = dfs(w, discovered)
    return discovered


def bfs(start_v):
    result = [start_v]
    queue = [start_v]
    while queue:
        v = queue.pop(0)
        for w in sorted(graph[v]):
            if w not in result:
                result.append(w)
                queue.append(w)
    return result


print(*dfs(V))
print(*bfs(V))