ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฐฉ๋ฒ•

๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์ค‘ DFS(Depth First Search์™€ BFS(Breadth First Search)๋ฅผ ๊ฐ„๋‹จํ•œ ์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด ์ดํ•ดํ•˜๊ณ ์ž ํ•œ๋‹ค. ๋‘ ๋ฐฉ์‹์€ ๊ฐ๊ฐ Stack๊ณผ Queue๋ฅผ ํ†ตํ•ด ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๊ทธ๋ž˜ํ”„ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ฒดํฌํ•˜์—ฌ ์ค‘๋ณต์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์„ ๋ฐฉ์ง€ํ•˜์—ฌ์•ผ ํ•œ๋‹ค.

 

๊ทธ๋ž˜ํ”„๋ฅผ ์ฝ”๋“œ๋กœ ๋‚˜ํƒ€๋‚ด๊ธฐ

Figure 1. ๊ทธ๋ž˜ํ”„ ์˜ˆ์‹œ

๊ทธ๋ฆผ 1์˜ ๊ทธ๋ž˜ํ”„์— ๋Œ€ํ•œ ๋…ธ๋“œ ์ •๋ณด๋ฅผ ์ฝ”๋“œ๋กœ ๋‚˜ํƒ€๋‚ด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A', 'E', 'F'],
    'D': ['B', 'G'],
    'E': ['C', 'H'],
    'F': ['C'],
    'G': ['D'],
    'H': ['E'],
}

DFS

Figure 2. Figure 1์˜ ๊ทธ๋ž˜ํ”„ DFS ํƒ์ƒ‰ ๊ณผ์ •

๊ทธ๋ฆผ 2๋Š” ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์‹œ์ž‘์œผ๋กœ ๋ชจ๋“  ๊ทธ๋ž˜ํ”„ ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ณผ์ •์ด๋‹ค.

  1. ๋ฃจํŠธ ๋…ธํŠธ์ธ A๋ฅผ Stack์— push ํ•˜๊ณ  visited๋กœ ํ‘œ์‹œ ํ•œ๋‹ค.
  2. A๋ฅผ popํ•˜๊ณ  A์˜ ์ž์‹๋…ธ๋“œ์ธ B C๋ฅผ ์ˆœ์„œ๋Œ€๋กœ stack์— push ํ•œ๋‹ค.
  3. Stack์€ LIFO์ด๋ฏ€๋กœ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด top ์œ„์น˜์— ์žˆ๋Š” ๋…ธ๋“œ๋“ค์ด ์šฐ์„ ์ ์œผ๋กœ ํƒ์ƒ‰๋˜๊ฒŒ ๋œ๋‹ค.
  4. ๋”ฐ๋ผ์„œ DFS๋Š” ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ์‹œ์ž‘์œผ๋กœ ๊นŠ์ด ์šฐ์„ ์œผ๋กœ ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋‹ค.

BFS

BFS๋Š” DFS์™€ ๋‹ฌ๋ฆฌ FIFO๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค. ๋”ฐ๋ผ์„œ DFS์™€ ๋‹ค๋ฅธ์ ์€ Stack์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ Queue๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ์‰ฝ๋‹ค.

 

Code

def sfs(graph, start, select):
    visited = {}
    lst = []

    lst.append(start)

    while lst:
        if select == 'DFS':
            node = lst.pop()
        else:
            node = lst.pop(0)

        if node not in visited:
            visited[node] = True
            lst.extend(graph[node])
    return visited.keys()
  • ์•ž์„œ ์–ธ๊ธ‰ํ•˜์˜€๋“ฏ์ด DFS์™€ BFS๋Š” ์‚ฌ์šฉํ•˜๋Š” Stack์„ ์‚ฌ์šฉํ•˜์—ฌ LIFO๋กœ ์ฒ˜๋ฆฌํ•˜๋ƒ Queue๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ FIFO๋กœ ์ฒ˜๋ฆฌํ•˜๋Š๋ƒ์— ๋”ฐ๋ฅธ ๋ฐฉ๋ฒ•์˜ ์ฐจ์ด์ด๋‹ค.
  • DFS๋Š” While๊ณผ stack์„ ํ†ตํ•ด ๊ตฌํ˜„ํ•  ์ˆ˜๋„ ์žˆ๊ณ , ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ†ตํ•ด ๊ตฌํ˜„ํ•  ์ˆ˜๋„ ์žˆ๋‹ค.
  • ๋‘ ๋ฐฉ์‹์˜ ์ฐจ์ด๋ฅผ ์‰ฝ๊ฒŒ ์ดํ•ดํ•˜๊ธฐ ์œ„ํ•ด select first sort๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜์˜€๋‹ค.
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€