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

Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] DFS & BFS

DFS( Depth-First Search)

  • ๊นŠ์ด์šฐ์„ ํƒ์ƒ‰(DFS) : ์Šคํƒ ์ž๋ฃŒ๊ตฌ์กฐ(ํ˜น์€ ์žฌ๊ท€ํ•จ์ˆ˜)๋ฅผ ์ด์šฉ, ๊นŠ์€ ๋ถ€๋ถ„์„ ์šฐ์„ ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
    1. ํƒ์ƒ‰ ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ๊ฐ‘์ž…ํ•˜๊ณ  ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค.
    2. ์Šคํƒ์˜ ์ตœ์ƒ๋‹จ ๋…ธ๋“œ์— ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๋Š” ์ž…์ ‘ํ•œ ๋…ธ๋“œ๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์žˆ์œผ๋ฉด ๊ทธ ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค. ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘ ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด ์Šคํƒ์—์„œ ์ตœ์ƒ๋‹จ ๋…ธ๋“œ๋ฅผ ๊บผ๋ƒ…๋‹ˆ๋‹ค.
    3. ๋”์ด์ƒ 2๋ฒˆ์˜ ๊ณผ์ •์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
  • DFS, BFS ๋‘˜ ๋‹ค ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ๊ฐ™๋‹ค
  • ์‹ค์ œ๋กœ๋Š” ์Šคํƒ์˜์—ญ(ํ˜น์€ ์žฌ๊ท€ํ•จ์ˆ˜)๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” BFS(๋ฐ˜๋ณต๋ฌธ)๋กœ ํ‘ธ๋Š” ๊ฒƒ์ด ๋” ๋น ๋ฅผ ์ˆ˜ ์žˆ๋‹ค

graph = [
  [],
  [2,3,8],
  [1,7],
  [1,4,5],
  [3,5],
  [3,4],
  [7],
  [2,6,8],
  [1,7]
]

visited = [False]*9

def dfs(graph, v, visited) :
  visited[v] = True
  print(v, end=" ")

  for i in graph[v] :
    if not visited[i] :
      dfs(graph, i, visited)

 

BFS (Breadth-First Search)

  • BFS๋Š” ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰
  • ๊ทธ๋ž˜ํ”„์—์„œ ๊ฐ€๊นŒ์šด ๋…ธ๋“œ๋ถ€ํ„ฐ ์šฐ์„ ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
  • ํ ์ž๋ฃŒ๊ตฌ์กฐ ์‚ฌ์šฉ
    1. ํƒ์ƒ‰ ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ํ์— ์‚ฝ์ž…ํ•˜๊ณ  ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค.
    2. ํ์—์„œ ๋…ธ๋“œ๋ฅผ ๊บผ๋‚ธ ๋’ค ํ•ด๋‹น ๋…ธ๋“œ์˜ ์ธ์ ‘ ๋…ธ๋“œ ์ค‘์—์„œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๋ฅผ ๋ชจ๋‘ ํ์— ์‚ฝ์ž…ํ•˜๊ณ  ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค.
    3. ๋” ์ด์ƒ 2๋ฒˆ์˜ ๊ณผ์ •์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

from collections import deque

graph = [
  [],
  [2,3,8],
  [1,7],
  [1,4,5],
  [3,5],
  [3,4],
  [7],
  [2,6,8],
  [1,7]
]

visited = [False]*9

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] :
        visited[i] = True
        queue.append(i)