BFS(G,s) # G는 그래프, s는 시작 정점
for v -> V
visited[v] = False # 방문여부를 체크할 수 있는 배열 초기화
visited[s] = True # 시작정점에 대해서 방문 체크
enqueue(Q,s) # 시작정점을 큐에 삽입
while Q # 큐가 존재할때 까지 반복
u= dequeue(Q) # 큐에서 노드 꺼내기 및 삭제
for v->L(u) # 해당 노드에서 갈 수 있는 모든 노드 탐색
if visited[v] == False # 방문여부 체크
visited[v] = True # 방문 체크
enqueue(Q,v) # 해당 노드를 큐에 삽입
📒 파이썬에서는 주로 Deque를 이용해서 구현한다.
import heapq # 우선순위 큐 구현을 위함
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph} # start로 부터의 거리 값을 저장하기 위함
distances[start] = 0 # 시작 값은 0이어야 함
queue = []
heapq.heappush(queue, [distances[start], start]) # 시작 노드부터 탐색 시작 하기 위함.
while queue: # queue에 남아 있는 노드가 없으면 끝
current_distance, current_destination = heapq.heappop(queue) # 탐색 할 노드, 거리를 가져옴.
if distances[current_destination] < current_distance: # 기존에 있는 거리보다 길다면, 볼 필요도 없음 + 방문여부 체크
continue
for new_destination, new_distance in graph[current_destination].items():
distance = current_distance + new_distance # 해당 노드를 거쳐 갈 때 거리
if distance < distances[new_destination]: # 알고 있는 거리 보다 작으면 갱신
distances[new_destination] = distance
heapq.heappush(queue, [distance, new_destination]) # 다음 인접 거리를 계산 하기 위해 큐에 삽입
return distances