graph = dict()
graph['A'] = ['B', 'C']
graph['B'] = ['A', 'D']
graph['C'] = ['A', 'G', 'H', 'I']
graph['D'] = ['B', 'E', 'F']
graph['E'] = ['D']
graph['F'] = ['D']
graph['G'] = ['C']
graph['H'] = ['C']
graph['I'] = ['C', 'J']
graph['J'] = ['I']
def bfs(graph, start_node):
visited = list()
need_visit = list()
need_visit.append(start_node)
while need_visit:
node = need_visit.pop(0)
if node not in visited:
visited.append(node)
need_visit.extend(graph[node])
return visited
print(bfs(graph, 'A'))
~~>
['A', 'B', 'C', 'D', 'G', 'H', 'I', 'E', 'F', 'J']
start_node A
가 처음에 bfs함수에 들어가게 되고 need_visit
에 append 된다.
node
에는 A가 들어가게 되고, 처음 visited
에는 A가 없으므로 need_visit
에 graph['A']의 값이 extend 된다. (-> ['B', 'C']
)
이 과정을 계속 반복하게 된다.
V
E
인접 리스트로 표현된 그래프 ( 위의 같은 경우 )
인접 행렬로 표현된 그래프