Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Djixtra shortest path solution in Clear category for The Cheapest Flight by vl.ev.ba
from collections import defaultdict
def cheapest_flight(costs: list, start: str, end: str) -> int:
# build undirected weighted graph
links=defaultdict(list)
for a, b, c in costs:
links[a].append((b,c))
links[b].append((a,c))
Q = [start]
C = {start: 0}
# find shortest path by Djixtra method
while Q:
nod=Q.pop(0)
if nod == end:
continue
for n1,c1 in links[nod]:
if n1 not in C or C[n1]>C[nod]+c1:
C[n1]=c1+C[nod]
Q.append(n1)
else:
if C[n1]>C[nod]+c1:
C[n1]= C[nod]+c1
Q.append(n1)
return C[end] if end in C else 0
May 6, 2026
Comments: