큐에 그래프의 정점들을 전부 집어넣고 최소값을 골라 그 정점에서 갈 수 있는 간선들을 찾아 값울 구하여 큐에 저장된 정점들의 값과 갈 수 있는 값을 비교하여 더 적은 값을 집어 넣고 그 중 가장 작은 값을 가진 정점에서 다시 반복한다.
import heapq
queue = []
mygraph = {
'A': {'B': 8, 'C': 1, 'D': 2},
'B': {},
'C': {'B': 5, 'D': 2},
'D': {'E': 3, 'F': 5},
'E': {'F': 1},
'F': {'A': 5}
}
def dijksta(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_node = heapq.heappop(queue)
if distances[current_node] < current_distance:
continue
for adjacent, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[adjacent]:
distances[adjacent] = distance
heapq.heappush(queue,[distance,adjacent])
return distances
print(dijksta(mygraph,'A'))