Aktualizovat u10/najkratsia_cesta.py
This commit is contained in:
parent
669d714d48
commit
d539210ca2
@ -1,27 +1,21 @@
|
||||
import heapq
|
||||
|
||||
|
||||
def shortest_path(number_of_nodes, connections):
|
||||
"""Vráť uzly najkratšej cesty z uzla 0 do uzla N - 1."""
|
||||
graph = [[] for i in range(number_of_nodes)]
|
||||
|
||||
for a, b, d in connections:
|
||||
graph[a].append((b, d))
|
||||
graph[b].append((a, d))
|
||||
|
||||
queue = [(0, [0])]
|
||||
|
||||
while queue:
|
||||
distance, path = heapq.heappop(queue)
|
||||
|
||||
best = min(queue)
|
||||
queue.remove(best)
|
||||
distance, path = best
|
||||
node = path[-1]
|
||||
|
||||
if node == number_of_nodes - 1:
|
||||
return path
|
||||
|
||||
for neighbor, d in graph[node]:
|
||||
if neighbor not in path:
|
||||
heapq.heappush(queue, (distance + d, path + [neighbor]))
|
||||
queue.append((distance + d, path + [neighbor]))
|
||||
|
||||
return []
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user