Introduction
Imagine trying to find the quickest way to get from your home to a new restaurant without wasting time or fuel. Navigation systems solve this problem by figuring out the shortest or fastest route among many possible paths.
Imagine you are in a large shopping mall trying to find the quickest way to a specific store. You look at the mall map and consider different corridors and escalators. By choosing the shortest path, you save time and avoid unnecessary walking.
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Start Point │──────▶│ Intersection │──────▶│ Destination │
└───────────────┘ └───────────────┘ └───────────────┘
│ │ ▲
│ │ │
└──────────────────────┴──────────────────────┘
Possible alternative pathsimport heapq def dijkstra(graph, start, end): queue = [(0, start)] distances = {node: float('inf') for node in graph} distances[start] = 0 while queue: current_distance, current_node = heapq.heappop(queue) if current_node == end: return current_distance if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(queue, (distance, neighbor)) return float('inf') # Example graph where keys are nodes and values are neighbors with distances graph = { 'A': {'B': 5, 'C': 1}, 'B': {'A': 5, 'C': 2, 'D': 1}, 'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8}, 'D': {'B': 1, 'C': 4, 'E': 3}, 'E': {'C': 8, 'D': 3} } print(dijkstra(graph, 'A', 'E'))