u10
This commit is contained in:
parent
cc16ccd516
commit
220a178128
32
u10/najkratsia_cesta.py
Normal file
32
u10/najkratsia_cesta.py
Normal file
@ -0,0 +1,32 @@
|
||||
def shortest_path(number_of_nodes, connections):
|
||||
neighbours = [[] for _ in range(number_of_nodes)]
|
||||
for node_a, node_b, distance in connections:
|
||||
neighbours[node_a].append([node_b, distance])
|
||||
neighbours[node_b].append([node_a, distance])
|
||||
|
||||
best = [None] * number_of_nodes
|
||||
best[0] = [0, [0]]
|
||||
visited = [False] * number_of_nodes
|
||||
|
||||
while True:
|
||||
node = None
|
||||
for candidate in range(number_of_nodes):
|
||||
if visited[candidate] or best[candidate] is None:
|
||||
continue
|
||||
if node is None or best[candidate] < best[node]:
|
||||
node = candidate
|
||||
|
||||
if node is None:
|
||||
return []
|
||||
if node == number_of_nodes - 1:
|
||||
return best[node][1]
|
||||
|
||||
visited[node] = True
|
||||
distance, path = best[node]
|
||||
for neighbour, edge_distance in neighbours[node]:
|
||||
if visited[neighbour]:
|
||||
continue
|
||||
|
||||
candidate = [distance + edge_distance, path + [neighbour]]
|
||||
if best[neighbour] is None or candidate < best[neighbour]:
|
||||
best[neighbour] = candidate
|
||||
Loading…
Reference in New Issue
Block a user