diff --git a/u10/najkratsia_cesta.py b/u10/najkratsia_cesta.py new file mode 100644 index 0000000..05283f4 --- /dev/null +++ b/u10/najkratsia_cesta.py @@ -0,0 +1,46 @@ +import heapq + +def shortest_path(number_of_nodes, connections): + + if number_of_nodes == 1: + return [0] + + grafik = {gx: [] for gx in range(number_of_nodes)} + for x, y, ves in connections: + grafik[x].append((y, ves)) + grafik[y].append((x, ves)) + + for nod in grafik: + grafik[nod].sort(key=lambda x: x[1]) + + distancia = {gg: float('inf') for gg in range(number_of_nodes)} + previ = {k: None for k in range(number_of_nodes)} + distancia[0] = 0 + + gns = [(0, 0)] + + while gns: + MODdistancia, MODnode = heapq.heappop(gns) + if MODdistancia > distancia[MODnode]: + continue + + for sused, ves in grafik[MODnode]: + vzdal = MODdistancia + ves + + if vzdal < distancia[sused]: + distancia[sused] = vzdal + previ[sused] = MODnode + heapq.heappush(gns, (vzdal, sused)) + + targ = number_of_nodes - 1 + if distancia[targ] == float('inf'): + return [] + + slach = [] + MODtarg = targ + while MODtarg is not None: + slach.append(MODtarg) + MODtarg = previ[MODtarg] + slach.reverse() + + return slach \ No newline at end of file