31 lines
871 B
Python
31 lines
871 B
Python
import heapq
|
|
|
|
|
|
def shortest_path(number_of_nodes, connections):
|
|
target = number_of_nodes - 1
|
|
|
|
neighbors = {node: [] for node in range(number_of_nodes)}
|
|
for a, b, distance in connections:
|
|
neighbors[a].append((b, distance))
|
|
neighbors[b].append((a, distance))
|
|
|
|
# Halda je usporiadana podla (vzdialenost, cesta), takze pri rovnakej
|
|
# vzdialenosti sa ako prva vyberie lexikograficky najmensia cesta.
|
|
queue = [(0, [0])]
|
|
visited = set()
|
|
|
|
while queue:
|
|
distance, path = heapq.heappop(queue)
|
|
node = path[-1]
|
|
if node in visited:
|
|
continue
|
|
if node == target:
|
|
return path
|
|
visited.add(node)
|
|
|
|
for neighbor, length in neighbors[node]:
|
|
if neighbor not in visited:
|
|
heapq.heappush(queue, (distance + length, path + [neighbor]))
|
|
|
|
return []
|