Dijkstra's algorithm
Алгоритм Дейкстры
This algorithm finds the lowest-cost routes from one starting point in a graph. It works when every connection has a cost of zero or more.
What does Dijkstra’s algorithm find?
Given a starting vertex, Dijkstra’s algorithm finds the shortest distance to every reachable vertex in a weighted graph. Here, “shortest” means the smallest sum of edge weights, not the fewest steps. If the weights are travel times, taking two quick roads can beat taking one slow road. Edges can be directed or undirected, and zero weights are allowed.
How the search works
Set the source’s distance to zero and all other distances to infinity. A finite distance is the cost of the best route found so far. Use a min-priority queue to process the vertex with the smallest tentative distance next.
When processing u, inspect every outgoing edge u → v. If dist[u] + weight(u, v) is less than dist[v], update dist[v] and add the new distance to the queue. This comparison and possible update is called relaxation. To return an actual route, also record u as the predecessor of v on each improvement. Follow those pointers backward from the destination, then reverse the result.
The key is that the smallest tentative distance is safe to finalize. Suppose a cheaper route to the chosen vertex existed. Look at the first vertex on that route that has not been finalized. Its predecessor has already been processed, so its tentative distance is no greater than the cost of reaching it along that route. Since later edges cannot reduce the cost, this tentative distance would be smaller than the one we chose, a contradiction.
A small example
Suppose S → T costs 8, S → A costs 3, and A → T costs 2. Processing S puts both T and A in the queue. A comes out first and improves T’s distance from 8 to 5. The best route is S → A → T. Stopping when T was first discovered would have returned the wrong answer.
Uses, trade-offs, and interview pitfalls
Dijkstra’s algorithm is used in network routing and as a baseline for route planning. For unit-weight edges, breadth-first search is simpler and runs in O(V + E) time. If edges can have negative weights, consider Bellman–Ford instead: a negative edge can make a route cheaper after Dijkstra would have finalized it.
In coding interviews, a common implementation uses adjacency lists and a binary min-heap. Push a new entry whenever a distance improves, and skip a popped entry if its distance no longer matches dist. With V vertices and E edges, this version takes O(V + E log(E + 1)) time, including distance initialization. If you only need one destination, stop when you pop it with its current distance. If the queue empties and the destination still has an infinite distance, it is unreachable.