Dijkstra’s algorithm is a popular graph traversal algorithm used to find the shortest path between nodes in a weighted graph. Developed by Edsger W. Dijkstra in 1956, it’s an efficient solution for finding the shortest path from a single source to all other nodes.
Overview
Dijkstra’s algorithm uses the following:
- Graph , where is the set of vertices and the set of edges.
- Edge weight , representing the cost or distance between nodes.
- Source vertex , from which shortest paths are calculated.
Applications
Dijkstra’s algorithm is widely used in GPS navigation, networking, and robotics, where shortest-path calculations are essential.
Algorithm Steps
- Initialize distances to all vertices as infinity, except the source vertex which is set to 0.
- Add all vertices to a priority queue (often a min-heap) where they are prioritized by distance.
- While the queue is not empty:
- Extract the vertex with the minimum distance.
- For each neighbor of :
- If , update and adjust ‘s priority in the queue.
- Repeat until all vertices are visited.
Pseudocode
Mathematical Explanation
Let denote the shortest distance from the source to any vertex . The algorithm ensures that by the time a vertex is removed from the priority queue, holds the minimum distance from to .
Distance Update Condition
For each edge with weight :
This update ensures that the shortest path to each neighbor is recalculated as necessary.
Example
Consider a graph represented by the following table:
Vertex | Neighbors (Edge Weight) |
---|---|
A | B (1), C (4) |
B | C (2), D (5) |
C | D (1) |
D |
Starting from , Dijkstra’s algorithm finds the shortest paths to other nodes:
Priority Queue Optimization
Using a min-heap for the priority queue ensures each extraction and update operation runs efficiently. In large graphs, this significantly reduces runtime.
Complexity
- Time Complexity: when implemented with a binary heap.
- Space Complexity: , as we store distances and a priority queue for each vertex.