[๋ฐฑ์ค€/python] 1260๋ฒˆ : DFS์™€ BFS

2021. 4. 5. 16:15

๋ฌธ์ œ

๊ทธ๋ž˜ํ”„๋ฅผ DFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ์™€ BFS๋กœ ํƒ์ƒ‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ์—๋Š” ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ณ , ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ด ์—†๋Š” ๊ฒฝ์šฐ ์ข…๋ฃŒํ•œ๋‹ค. ์ •์  ๋ฒˆํ˜ธ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ๊นŒ์ง€์ด๋‹ค.

 

์ž…๋ ฅ

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

 

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— DFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ, ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. V๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ๋œ ์ ์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

์ •๋‹ต

import sys
from collections import deque

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

graph = {i: [] for i in range(1, N+1)}
for i in range(M):
    k, v = map(int, sys.stdin.readline().split())
    graph[k].append(v)
    graph[v].append(k)

for k in graph:
    graph[k].sort()


def DFS(graph, root):
    visited = []
    stack = [root]

    while stack:
        n = stack.pop()
        if n not in visited:
            visited.append(n)
            stack.extend(sorted(graph[n], reverse=True))
    return visited


def BFS(graph, root):
    visited = []
    queue = deque([root])

    while queue:
        n = queue.popleft()
        if n not in visited:
            visited.append(n)
            queue.extend(graph[n])
    return visited

print(' '.join(list(map(str, DFS(graph, V)))))
print(' '.join(list(map(str, BFS(graph, V)))))

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

graph = {i: [] for i in range(1, N+1)}
for i in range(M):
    k, v = map(int, sys.stdin.readline().split())
    graph[k].append(v)
    graph[v].append(k)
    
for k in graph:
    graph[k].sort()

์ •์ ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๊ฐ„์„ ์˜ ์ˆ˜ M, ์‹œ์ž‘ ๋…ธ๋“œ V๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.

์ •์ ์˜ ๊ฐœ์ˆ˜๋งŒํผ key๋ฅผ ๋งŒ๋“ค์–ด value๊ฐ€ ๋นˆ ๋ฆฌ์ŠคํŠธ์ธ ๋”•์…”๋„ˆ๋ฆฌ graph๋ฅผ ๋งŒ๋“ ๋‹ค.

์–‘๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ„์„ ์„ ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์„ ์„œ๋กœ๊ฐ€ key์™€ value๊ฐ€ ๋˜๋„๋ก graph์— ์ €์žฅํ•œ๋‹ค.

์ •์ ์ด ์—ฌ๋Ÿฌ ๊ฐœ์ธ ๊ฒฝ์šฐ ์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด value๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.

 

์ดํ›„์˜ DFS์™€ BFS๋Š” ์•„๋ž˜ ํฌ์ŠคํŒ…์—์„œ ์ž์„ธํ•˜๊ฒŒ ์„ค๋ช…ํ•ด๋‘์—ˆ๋‹ค.

2021.04.05 - [๐Ÿ”์•Œ๊ณ ๋ฆฌ์ฆ˜/๐Ÿ”…๊ฐœ๋…์ •๋ฆฌ] - [ํŒŒ์ด์ฌ/python] DFS์™€ BFS

 

[ํŒŒ์ด์ฌ/python] DFS์™€ BFS

๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ DFS์™€ ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ BFS๋Š” ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋Œ€ํ‘œ์ ์ธ ๋ฐฉ๋ฒ•์ด๋‹ค. ๊ทธ๋ž˜ํ”„๋ž€ ์ •์  node์™€ ์ •์ ์„ ์—ฐ๊ฒฐํ•˜๋Š” ๊ฐ„์„  edge๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค. ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ DFS DFS๋Š” Depth Fir

ye333.tistory.com

 

728x90

BELATED ARTICLES

more