Day 11: Graph Algorithms
1. Dijkstra’s Algorithm
import heapq
def dijkstra(graph, start):
# Initialize distances and priority queue
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
priority_queue = [(0, start)] # (distance, vertex)
while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)
# If the popped vertex distance is greater than recorded, skip
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex]:
distance = current_distance + weight
# Only consider this new path if it's better
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
# Example Usage
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
print(dijkstra(graph, 'A'))2. Bellman-Ford Algorithm
3. Comparison of Dijkstra’s and Bellman-Ford Algorithms
4. Applications of Shortest Path Algorithms
5. Recommended Practice Problems
6. Key Concepts to Remember
Last updated