53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
def shortest_path(number_of_nodes, connections):
|
|
if number_of_nodes == 1:
|
|
return [0]
|
|
|
|
# zoznam susedov
|
|
susedy = [[] for _ in range(number_of_nodes)]
|
|
for node_a, node_b, distance in connections:
|
|
susedy[node_a].append((node_b, distance))
|
|
|
|
susedy[node_b].append((node_a, distance)) # obojsmerne (+ node)
|
|
|
|
|
|
# init
|
|
distancii = [float("inf")] * number_of_nodes
|
|
paths = [[] for _ in range(number_of_nodes)]
|
|
|
|
boli = [False] * number_of_nodes
|
|
|
|
distancii[0] = 0
|
|
paths[0] = [0]
|
|
|
|
|
|
for _ in range(number_of_nodes):
|
|
teraz = -1
|
|
|
|
# najblizsi node
|
|
for node in range(number_of_nodes):
|
|
if not boli[node] and distancii[node] != float("inf"):
|
|
if teraz == -1:
|
|
teraz = node
|
|
|
|
elif (distancii[node], paths[node]) < (distancii[teraz], paths[teraz]):
|
|
teraz = node
|
|
|
|
|
|
if teraz == -1:
|
|
break
|
|
|
|
boli[teraz] = True
|
|
|
|
# check susedov
|
|
for sused, weight in susedy[teraz]:
|
|
if not boli[sused]:
|
|
|
|
new_dist = round(distancii[teraz] + weight, 9)
|
|
new_path = paths[teraz] + [sused]
|
|
|
|
if (new_dist, new_path) < (distancii[sused], paths[sused]):
|
|
distancii[sused] = new_dist # update dist + path
|
|
paths[sused] = new_path
|
|
|
|
|
|
return paths[number_of_nodes - 1] |