Certainly! Dijkstra's algorithm is a greedy algorithm used to find the shortest path from a source node to all other nodes in a weighted graph with non-negative edge weights. It works by iteratively selecting the node with the smallest tentative distance and updating the distances of its neighbors.
Algorithm Steps:
-
Initialize:
- Assign a distance value to every node:
0 for the source node and ∞ (infinity) for all others.
- Mark all nodes as unvisited.
- Use a priority queue (min-heap) to efficiently retrieve the node with the smallest distance.
-
Main Loop:
- Extract the node
u with the smallest distance from the priority queue.
- For each neighbor
v of u, calculate the tentative distance (distance[u] + weight(u, v)).
- If this tentative distance is less than the current distance of
v, update v's distance and add it to the priority queue.
- Mark
u as visited.
-
Termination:
- The algorithm ends when the priority queue is empty or all nodes have been visited.
Example Implementation (Python)
Let's implement Dijkstra's algorithm using a min-heap (priority queue) for efficiency.
Graph Representation (Adjacency List)
import heapq
def dijkstra(graph, start):
# Initialize distances with infinity and set start node distance to 0
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# Priority queue: (distance, node)
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
# Skip if we already found a better path
if current_distance > distances[current_node]:
continue
# Check all neighbors
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
# Update if a shorter path is found
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
Example Graph
Consider the following weighted graph:
A
/ | \
2 1 3
/ | \
B -- C -- D
3 1
- Adjacency List Representation:
graph = {
'A': {'B': 2, 'C': 1, 'D': 3},
'B': {'A': 2, 'C': 3},
'C': {'A': 1, 'B': 3, 'D': 1},
'D': {'A': 3, 'C': 1}
}
Running Dijkstra's Algorithm
shortest_distances = dijkstra(graph, 'A')
print(shortest_distances)
Output
{'A': 0, 'B': 2, 'C': 1, 'D': 2}
Explanation:
- The shortest path from
A to B is A → B (distance = 2).
- The shortest path from
A to C is A → C (distance = 1).
- The shortest path from
A to D is A → C → D (distance = 1 + 1 = 2).
Time Complexity
- Using a min-heap (priority queue):
- O((V + E) log V), where
V is the number of vertices and E is the number of edges.
- Without optimization (using an array):
- O(V²) (slower for large graphs).
Key Points
- Dijkstra's algorithm does not work with negative edge weights (use Bellman-Ford instead).
- It is greedy, always selecting the closest unvisited node.
- The priority queue ensures efficiency by always processing the next best candidate.
Would you like a step-by-step breakdown of how the algorithm processes the example graph?