u10
This commit is contained in:
parent
3382dbecc6
commit
5c1173266d
92
u10/najkratsia_cesta.py
Normal file
92
u10/najkratsia_cesta.py
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
import heapq
|
||||||
|
import math
|
||||||
|
|
||||||
|
def shortest_path(number_of_nodes, connections):
|
||||||
|
if number_of_nodes == 1:
|
||||||
|
return [0]
|
||||||
|
|
||||||
|
target = number_of_nodes - 1
|
||||||
|
|
||||||
|
# Перебирает номера всех городов по порядку и каждому городу дает свой индекс
|
||||||
|
neighbors = {}
|
||||||
|
for indx in range(number_of_nodes):
|
||||||
|
neighbors[indx] = []
|
||||||
|
|
||||||
|
# Для каждой дороги из connections соединяет два города (a и b) в обе стороны
|
||||||
|
for a, b, weight in connections:
|
||||||
|
neighbors[a].append((b, weight))
|
||||||
|
neighbors[b].append((a, weight))
|
||||||
|
|
||||||
|
# distances[node] мин известное расстояние от 0 до node
|
||||||
|
distances = {}
|
||||||
|
for node in range(number_of_nodes): #in range значит что выдает от 0 до числа в скобка -1
|
||||||
|
distances[node] = math.inf # math.inf это +беск
|
||||||
|
|
||||||
|
# predecessors[node] из какого предыдущего узла мы пришли в node по лучшему пути
|
||||||
|
predecessors = {}
|
||||||
|
for node in range(number_of_nodes): #in range значит что выдает от 0 до числа в скобка -1
|
||||||
|
predecessors[node] = None
|
||||||
|
|
||||||
|
visited = [] # Заменили set() на обычный пустой список
|
||||||
|
|
||||||
|
distances[0] = 0 # Расстояние от стартового узла до самого себя равно 0
|
||||||
|
|
||||||
|
priority_queue = [(0, [0], 0)] # стартовый маршрут
|
||||||
|
|
||||||
|
while priority_queue:
|
||||||
|
current_dist, current_path, u = heapq.heappop(priority_queue)
|
||||||
|
# heapq.heappop сравнивает переменные и выбирает найменьшое в current_path например
|
||||||
|
# [0, 1, 2] < [0, 1, 3] так как сравнивает по очереди 0 = 0 1=1 2<3 значит выбираем 2
|
||||||
|
|
||||||
|
if u in visited:
|
||||||
|
continue
|
||||||
|
|
||||||
|
visited.append(u)
|
||||||
|
|
||||||
|
# лучший путь
|
||||||
|
if u == target:
|
||||||
|
break
|
||||||
|
|
||||||
|
for v, weight in neighbors[u]:
|
||||||
|
# Если сосед уже есть в текущем пути (защита от циклов при весе 0)
|
||||||
|
if v in visited or v in current_path:
|
||||||
|
continue
|
||||||
|
|
||||||
|
candidate_dist = current_dist + weight # новое суммарное расстояние
|
||||||
|
candidate_path = current_path + [v] # новый маршрут
|
||||||
|
|
||||||
|
# Проверяемстал ли путь короче или при равной длине он лексикографически меньше
|
||||||
|
is_shorter = candidate_dist < distances[v]
|
||||||
|
# Проверяем одинаковая ли длина у нового пути и старого рекорда
|
||||||
|
same_distance = math.isclose(candidate_dist, distances[v])
|
||||||
|
# Если длина одинаковая проверяем лучше ли новый путь по порядку городов (по алфавиту)
|
||||||
|
is_lex_better = False
|
||||||
|
if same_distance:
|
||||||
|
# _reconstruct_path идет по массиву от конца к началу [0 1 2] = [2 1 0]
|
||||||
|
old_path = reconstruct_path(predecessors, v)
|
||||||
|
if candidate_path < old_path:
|
||||||
|
is_lex_better = True
|
||||||
|
|
||||||
|
if is_shorter or is_lex_better:
|
||||||
|
distances[v] = candidate_dist
|
||||||
|
# Запоминаем лучшего предшественника
|
||||||
|
predecessors[v] = u
|
||||||
|
new_item = (candidate_dist, candidate_path, v)
|
||||||
|
heapq.heappush(priority_queue, new_item)
|
||||||
|
|
||||||
|
# Если расстояние до цели так и осталось бесконечностью нерешаемо
|
||||||
|
if distances[target] == math.inf:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return reconstruct_path(predecessors, target)
|
||||||
|
|
||||||
|
|
||||||
|
def reconstruct_path(predecessors, end_node):
|
||||||
|
# reconstruct_path идет по массиву от конца к началу [0 1 2] = [2 1 0]
|
||||||
|
path = []
|
||||||
|
current = end_node
|
||||||
|
while current is not None:
|
||||||
|
path.append(current)
|
||||||
|
current = predecessors[current]
|
||||||
|
path.reverse()
|
||||||
|
return path
|
||||||
Loading…
Reference in New Issue
Block a user