43. Dijkstra's Algorithm: Detailed Implementation Steps
Let's formalize the steps for Dijkstra's:
- Initialization: Create a distance array
dist(all set to infinity, source set to 0) and a setvisited(empty). - Priority Queue Setup: Insert the source node (distance 0) into a Min Heap.
- Iteration: While the Min Heap is not empty:
a. Extract the node
Uwith the minimum distance (the greedy step). b. IfUhas already been processed (in thevisitedset), continue. c. MarkUas visited. d. Relaxation: For every neighborVofU: * Calculate the tentative new distance:new_dist = dist[U] + weight(U, V). * Ifnew_dist < dist[V], updatedist[V]tonew_distand insert/updateVin the priority queue.
- Complexity: With a Fibonacci heap, O(E + V log V). With a standard Binary Heap (more common), O((V + E) log V).