bfs

from collections import deque

def bfs(graph,start,visited):

    # ๋ฏธ๋ฆฌ visited ๋งŒ๋“ฆ
    bfs_visited = []

    # ์ˆ˜ํ–‰, ๋ฐฉ๋ฌธํ‘œ์‹œ
    print(start, end=' ')
    visited.append(start)
    # ์‹œ์ž‘์ ์˜ ์ธ์ ‘๋…ธ๋“œ ํ์— ์‚ฝ์ž…
    q = dequq()
    # ์ธ์ ‘๋…ธ๋“œ๊ฐ€ ๋ณต์ˆ˜๋ผ๋ฉด, extend ๋กœ ์ธ์ ‘๋…ธ๋“œ๋“ค์„ q์— ์ถ”๊ฐ€ํ•˜๋Š”๊ฒŒ ๋‚˜์Œ
    q.extend(graph[start])

    while queue:
        # ํ์—์„œ ๊บผ๋ƒ„
        v = queue.popleft()
        # ๊บผ๋ƒˆ๋Š”๋ฐ ๋ฐฉ๋ฌธ ์•ˆ ๋˜์–ด ์žˆ์œผ๋ฉด
        if v not in visited:
            # ์ˆ˜ํ–‰
            print(v, end=' ')
            # ๋ฐฉ๋ฌธํ‘œ์‹œ
            visited.append(v)
            # ํ์— ์ธ์ ‘๋…ธ๋“œ ์ถ”๊ฐ€
            q.extend(graph[v])

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

bfs(graph,1)

Last updated