๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #1260 DFS์™€ BFS (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

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

2. ์ฝ”๋“œ

solution1.py

# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline
from collections import deque

N, M, V = map(int, input().split())
graph = [[] for _ in range(N+1)]
for i in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

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

def dfs(graph, v, visited):
    #ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
    visited[v] = True
    print(v, end=' ')
    #ํ˜„์žฌ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋ฐฉ๋ฌธ
    for i in graph[v]: #์ •์ ์˜ ์ธ์ ‘๋…ธ๋“œ๋“ค์˜ ํ™•์ธ
        if not visited[i]: #์ธ์ ‘๋…ธ๋“œ๋“ค ์ค‘์— ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๊ฐ€ ์žˆ๋‹ค๋ฉด
            dfs(graph, i, visited) #๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ


def bfs(graph, start, visited):
    queue = deque([start])
    visited[start] = True #ํ˜„์žฌ ๋…ธ๋“œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
    while queue:
        v = queue.popleft()
        print(v, end=' ')

        for i in graph[v]: #ํ•ด๋‹น ๋…ธ๋“œ์˜ ์ธ์ ‘ ๋…ธ๋“œ๋“ค ํ™•์ธ
            if not visited[i]:#์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€์•Š์€ ์ธ์ ‘๋…ธ๋“œ๋“ค์„
                queue.append(i) #์ฐพ๋Š” ์กฑ์กฑ ๋‹ค ํ์— ์‚ฝ์ž…
                visited[i] = True #๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ

visited = [False]*(N+1)
dfs(graph, V, visited)
visited = [False]*(N+1)
print()
bfs(graph, V, visited)

3. ํšŒ๊ณ 

  • dfs, bfs ๊ธฐ์ดˆ ๋ฌธ์ œ๋กœ ํ’€๊ธฐ ์ข‹์•˜๋‹ค.
  • graph์ •๋ณด๋ฅผ ์ž…๋ ฅ ๋ฐ›์€ ๋’ค sort()๋ฅผ ๊ผญ ํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค.(์ •์  ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•œ๋‹ค๋Š” ์กฐ๊ฑด์ด ์กด์žฌํ•œ๋‹ค.)
  • visited = [False]*(N+1)๋ฅผ ํ†ตํ•ด visited ์ดˆ๊ธฐํ™”ํ•œ ํ›„ bfs๋ฅผ ์ˆ˜ํ–‰ํ•ด์•ผํ•œ๋‹ค.
  • print()๋ฅผ ํ†ตํ•ด dfs ํ›„์— ์ค„๋ฐ”๊ฟˆ์„ ํ•ด์ค˜์•ผํ•œ๋‹ค. ์ด๊ฑธ ์•ˆํ•ด์„œ ์ถœ๋ ฅ ํ˜•์‹์ด ์ž˜๋ชป๋˜์—ˆ๋‹ค๊ณ  ๋–ด์—ˆ๋‹ค ใ… ใ