Skip to content

Instantly share code, notes, and snippets.

@ourway
Created January 22, 2023 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ourway/a41351fc34bb933309c86c17e4beb5d3 to your computer and use it in GitHub Desktop.
Save ourway/a41351fc34bb933309c86c17e4beb5d3 to your computer and use it in GitHub Desktop.
Here is an example of a Python program that calculates the shortest route between two points using the Dijkstra algorithm
import heapq
def shortest_route(start, end, graph):
# Initialize the heap with the starting point
heap = [(0, start)]
# Initialize a dictionary to keep track of the best distances to each point
best_distances = {start: 0}
# Initialize a dictionary to keep track of the previous point in the best route to each point
previous_points = {}
while heap:
# Get the point with the best distance from the heap
(distance, current) = heapq.heappop(heap)
# If we've reached the end point, we're done
if current == end:
break
# Otherwise, check the neighboring points
for neighbor, weight in graph[current].items():
# Calculate the distance to the neighbor through the current point
new_distance = distance + weight
# If the new distance is better than the best distance we've seen so far, update it
if neighbor not in best_distances or new_distance < best_distances[neighbor]:
best_distances[neighbor] = new_distance
previous_points[neighbor] = current
heapq.heappush(heap, (new_distance, neighbor))
# Once we've finished calculating the best distances, use the previous_points dictionary to find the shortest route
route = []
current = end
while current != start:
route.append(current)
current = previous_points[current]
route.append(start)
route.reverse()
return route
# Example usage:
graph = {
"A": {"B": 5, "D": 9, "E": 2},
"B": {"C": 2},
"C": {"D": 3},
"D": {"B": 2, "E": 4},
"E": {"C": 6},
}
print(shortest_route("A", "C", graph))
# Output: ['A', 'E', 'D', 'C']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment