Dijkstra's algorithm is a fundamental graph algorithm that solves the shortest path problem in weighted graphs. Given a graph with non-negative edge weights, it finds the shortest path from a source vertex to all other vertices. The algorithm uses a greedy approach, always selecting the closest unvisited vertex, and guarantees optimal solutions. This makes it essential for applications like GPS navigation and network routing.
Dijkstra's algorithm relies on three essential components. First, the distance array tracks the shortest known distance from the source to each vertex, initialized with zero for the source and infinity for all others. Second, the visited set marks which vertices have been processed. Third, the relaxation process is the core mechanism that updates distances when shorter paths are discovered, comparing if the distance through a current vertex is shorter than the known distance.
Let's execute Dijkstra's algorithm step by step on this graph, starting from vertex A. We initialize the distance to A as zero and all other distances as infinity. We mark A as visited, shown in yellow, and update the distances to its neighbors B and D. The algorithm continues by always selecting the unvisited vertex with the minimum distance, systematically building the shortest path tree.
The relaxation process is the core mechanism of Dijkstra's algorithm. For each edge from vertex u to vertex v, we check if going through u provides a shorter path to v. The mathematical condition is: if distance of u plus the edge weight is less than the current distance to v, then we update v's distance. This process ensures we always maintain the shortest known distances and guarantees the algorithm's optimality.
Dijkstra's algorithm has excellent time complexity: O of V plus E times log V with a binary heap, or O of V squared with a simple array implementation. The space complexity is O of V. This efficiency makes it ideal for real-world applications like GPS navigation, network routing, social network analysis, and game pathfinding. The algorithm systematically finds optimal paths, as shown in this example where the shortest path from S to T costs 7 units.