Overview
Dijkstra’s algorithm finds the shortest path between two vertices in a weighted graph. It uses a priority queue (min-heap) to efficiently select the next vertex with the minimum distance from the starting vertex.This implementation works with both
AdjacencyListWeightedGraph and AdjacencyMatrixWeightedGraph from the DSA package.Functions
shortest_path
Computes weight and predecessor tables using Dijkstra’s Algorithm.dijkstra.py:5
graph(Graph): The graph to searchstart(str): The starting vertex labelend(str): The ending vertex labeldebug(bool): Optional flag to display weight table during computation
tuple: A tuple containing:- Weight table (dict): Maps each vertex to its shortest distance from start
- Predecessor table (dict): Maps each vertex to its predecessor in the shortest path
KeyError: If start or end vertex is not in the graph
find_path
Returns the shortest path between two vertices.dijkstra.py:56
graph(Graph): The graph to searchstart(str): The starting vertex labelend(str): The ending vertex labeldebug(bool): Optional flag to display weight and predecessor tables
list: A list of vertex labels forming the shortest path from start to end
KeyError: If start or end vertex is not in the graph, or if no path exists
Usage Examples
Algorithm Details
The implementation uses:- Min-Heap Priority Queue: Efficiently selects the next vertex with minimum distance (dijkstra.py:29)
- Weight Table: Tracks the shortest known distance to each vertex (dijkstra.py:26)
- Predecessor Table: Stores the predecessor of each vertex in the shortest path (dijkstra.py:27)
- Visited Set: Prevents reprocessing of vertices (dijkstra.py:28)
The algorithm terminates early when the destination vertex is reached (dijkstra.py:40-41), optimizing performance for single-pair shortest path queries.
Time Complexity
- Time Complexity: O((V + E) log V) where V is the number of vertices and E is the number of edges
- Space Complexity: O(V) for storing the weight table, predecessor table, and priority queue
Related
- Prim’s Algorithm - Similar approach for finding minimum spanning trees
- Graph Data Structure - Learn about graph representations