The Dijkstra Algorithm falls under the category of "Shortest Path" problems in graphs. This is a classic optimization problem in graph theory, where the goal is to find the lowest weight path between two vertices in a weighted graph. The Dijkstra algorithm is particularly efficient for graphs with non-negative weights on the edges. Solving shortest path problems is crucial in various areas, such as computer networks, route planning, and logistics.
Initialization:
- Select a source vertex;
- Create a HashTable to store the vertices that have already been visited;
- Create a dictionary to store the distances from the source to each vertex, initializing the distance from the source to itself as 0;
- Create a Min-heap queue and add the source vertex with distance 0;
Processing:
- While the queue is not empty and the number of visited vertices is less than the number of vertices in the graph:
- Retrieve the vertex with the smallest accumulated distance from the queue;
- If we are looking for the shortest path to a specific vertex, at this step, we can check if the current vertex is the destination vertex and terminate the neighbor processing loop;
- If the current vertex has already been visited, skip to the next vertex and go back to step 5.1;
- Add the current vertex to the HashTable of visited vertices;
- For each neighbor of the current vertex in the graph:
- Calculate the accumulated distance to the current vertex + the distance from the current vertex to the neighbor;
- If the neighbor is not in the distance dictionary or the accumulated distance is less than the neighbor's distance in the dictionary:
- Update the neighbor's distance in the dictionary;
- Add the neighbor to the queue with the accumulated distance to enter the priority queue;
Finalization:
- If we are looking for the shortest path to a specific vertex, we can terminate when the destination vertex is found;
- Then, we traverse the dictionary from the destination to the source to obtain the shortest path;
- If we are looking for the shortest path to all vertices, we can terminate when the queue is empty or all vertices have been visited;
- Then, we can return the distance dictionary.
To run this demo, you need to install the following packages:
pip install networkx
pip install matplotlib