avp26/u10/najkratsia_cesta.py
2026-11-17 14:44:42 +01:00

46 lines
1.2 KiB
Python

def shortest_path(number_of_nodes, connections):
start = 0
end = number_of_nodes - 1
if start == end:
return [0]
dist = []
path = []
for i in range(number_of_nodes):
dist.append(None)
path.append([])
dist[start] = 0
path[start] = [start]
change = True
while change:
change = False
for i in connections:
first = i[0]
to = i[1]
length = i[2]
for i,j in [(first, to), (to, first)]:
if dist[i] is None:
continue
if j in path[i]:
continue
newdist = dist[i] + length
newpath = path[i] + [j]
bet = False
if dist[j] is None:
bet = True
elif newdist < dist[j]:
bet = True
elif newdist == dist[j]:
if newpath < path[j]:
bet = True
if bet:
dist[j] = newdist
path[j] = newpath
change = True
return path[end]