- 특정 지점에서 다른 특정 지점까지의 최단 경로를 구하는 문제
- 그래프 이용
- 그래프에서 여러 개의 노드가 있을 때, 특정한 노드에서 출발하여 다른 노드로 가는 각각의 최단 경로를 구해주는 알고리즘
- 출발 노드를 설정한다.
- 최단 거리 테이블을 int(1e9)로 초기화한다.
- 방문하지 않은 노드 중에서 최단 거리가 가장 짧은 노드를 선택한다.
- 해당 노드를 거쳐 다른 노드로 가능 비용을 계산하여 최단 거리 테이블을 갱신한다.
- 위 과정에서 3번과 4번을 반복한다.
import heapq # 우선순위 큐 구현을 위함
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = []
heapq.heappush(queue, [distances[start], start])
while 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
- 힙은 완전 이진 트리로서 재구성 하는데 트리의 높이만큼의 비용이 발생 O(H) = O(logN)
- 즉, O(E) + O(ElogE) 이므로 총 시간 복잡도는 **O(ElogE)**입니다.