diff --git a/u10/najkratsia_cesta.py b/u10/najkratsia_cesta.py new file mode 100644 index 0000000..8859cb8 --- /dev/null +++ b/u10/najkratsia_cesta.py @@ -0,0 +1,30 @@ +import heapq + + +def shortest_path(number_of_nodes, connections): + target = number_of_nodes - 1 + + neighbors = {node: [] for node in range(number_of_nodes)} + for a, b, distance in connections: + neighbors[a].append((b, distance)) + neighbors[b].append((a, distance)) + + # Halda je usporiadana podla (vzdialenost, cesta), takze pri rovnakej + # vzdialenosti sa ako prva vyberie lexikograficky najmensia cesta. + queue = [(0, [0])] + visited = set() + + while queue: + distance, path = heapq.heappop(queue) + node = path[-1] + if node in visited: + continue + if node == target: + return path + visited.add(node) + + for neighbor, length in neighbors[node]: + if neighbor not in visited: + heapq.heappush(queue, (distance + length, path + [neighbor])) + + return []