u10
This commit is contained in:
parent
2ee8693f8b
commit
82e430e5ba
30
u10/najkratsia_cesta.py
Normal file
30
u10/najkratsia_cesta.py
Normal file
@ -0,0 +1,30 @@
|
||||
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 []
|
||||
Loading…
Reference in New Issue
Block a user