Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜] BFS(๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰) ๊ฐœ๋… ๋ฐ ๊ตฌํ˜„(ํŒŒ์ด์ฌ)

meeeeejin 2021. 3. 23. 12:54

๋ชฉ์ฐจ

  • BFS์˜ ๊ฐœ๋…
  • BFS์˜ ์žฅ๋‹จ์ 
  • BFS์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„
  • BFS์˜ ๊ตฌํ˜„

 

 

 

BFS(๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰)์ด๋ž€?

  • BFS(Breadth First Search) ๋˜๋Š” ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰์ด๋ผ๊ณ  ํ•จ
  • ์‹œ์ž‘ ์ •์ ์œผ๋กœ๋ถ€ํ„ฐ ๊ฐ€๊นŒ์šด ์ •์ ์„ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๋Š” ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฐฉ๋ฒ•
  • ํ(queue)๋ฅผ ์ด์šฉํ•ด ๋ฐฉ๋ฌธํ•œ ์ •์ ๋“ค์„ ์ฐจ๋ก€๋กœ ์ €์žฅํ•˜๊ณ  ๊บผ๋ƒ„

 

 

BFS์˜ ๋™์ž‘ ๊ณผ์ •

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

 

BFS์˜ ์žฅ๋‹จ์ 

์žฅ์ 

  • ์‹œ์ž‘ ์ •์ ์—์„œ ๋ชฉํ‘œ ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ธธ์ด ๊ฒฝ๋กœ๋ฅผ ๋ณด์žฅํ•œ๋‹ค. 

 

๋‹จ์ 

  • ๊ฒฝ๋กœ๊ฐ€ ๋งค์šฐ ๊ธธ ๊ฒฝ์šฐ, ํƒ์ƒ‰ ๊ฐ€์ง€๊ฐ€ ๊ธ‰๊ฒฉํžˆ ์ฆ๊ฐ€ํ•จ์— ๋”ฐ๋ผ ๋งŽ์€ ๊ธฐ์–ต ๊ณต๊ฐ„์ด ํ•„์š”ํ•˜๋‹ค. 
  • ๋‹ต์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์œ ํ•œ ๊ทธ๋ž˜ํ”„(finite graph)์˜ ๊ฒฝ์šฐ์—๋Š” ๋ชจ๋“  ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•œ ํ›„ ์‹คํŒจ๋กœ ๋๋‚œ๋‹ค. 
  • ๋ฌดํ•œ ๊ทธ๋ž˜ํ”„(infinite graph)์˜ ๊ฒฝ์šฐ์—๋Š” ๋‹ต์„ ์ฐพ์ง€ ๋ชปํ•˜๊ณ , BFS๊ฐ€ ๋๋‚˜์ง€๋„ ์•Š๋Š”๋‹ค. 

 

 

 

BFS์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„

  • N: ๋…ธ๋“œ์˜ ์ˆ˜, E: ๊ฐ„์„ ์˜ ์ˆ˜
  • ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ํ‘œํ˜„๋œ ๊ทธ๋ž˜ํ”„: O(N+E)
  • ์ธ์ ‘ ํ–‰๋ ฌ๋กœ ํ‘œํ˜„๋œ ๊ทธ๋ž˜ํ”„: O(N^2)

 

 

 

BFS์˜ ๊ตฌํ˜„

# graph[i]๋Š” i๋ฒˆ์งธ ๋…ธ๋“œ์™€ ์ธ์ ‘ํ•œ ๋…ธ๋“œ ๋ฒˆํ˜ธ๋ฅผ ํฌํ•จ
graph = [
    [1, 2, 4],
    [0, 2],
    [0, 1, 3, 4],
    [2, 4],
    [0, 2, 3]
]

# ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๋ฆฌ์ŠคํŠธ
visited = [False] * 5

# queue ์ž๋ฃŒ๊ตฌ์กฐ ์‚ฌ์šฉ์„ ์œ„ํ•ด
from collections import deque

# BFS
def bfs(start):
    # ์‹œ์ž‘ ์ •์  ํ ์‚ฝ์ž… ๋ฐ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
    queue = deque([start])
    visited[start] = True
    # ํ๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
    while queue:
        v = queue.popleft()
        print(v, end = ' ') # 0 1 2 4 3
        for x in graph[v]:
            if not visited[x]:
                queue.append(x)
                visited[x] = True
                
# 0์„ ์‹œ์ž‘ ์ •์ ์œผ๋กœ BFS
bfs(0)

 

 

 

 

์ฐธ๊ณ 

 

 

 

728x90