Builds onGraph BFS and DFSHeap and top K
01The idea
When every edge counts the same, breadth-first search finds the fewest edges. When edges have different costs, such as road lengths or ticket prices, the fewest edges is not always the cheapest route. Dijkstra's algorithm finds the cheapest route when every cost is zero or more.
Dijkstra's algorithm grows a set of settled nodes, whose cheapest cost is final. Each round it settles one more:
- Pick the unsettled node with the lowest known cost. A min-heap gives it in O(log n).
- That cost is final. Every other unsettled node already costs at least as much, and costs only grow along a route, so no detour can come back cheaper.
- For each edge out of the node, check whether going through this node is cheaper for the neighbour. If it is, lower the neighbour's cost and push the new cost onto the heap. This step is called relaxing the edge.
The heap may hold several entries for the same node, because the search can find a cheaper cost after it pushed an older one. When an old entry comes out, its cost is higher than the node's recorded cost. Skip it. That is simpler than deleting entries from the heap.
02How to spot it
Use Dijkstra's algorithm when:
- the graph has weights, and the question asks for the cheapest, shortest or fastest route
- every weight is zero or positive
- you need the cost from one source, to one target or to every node
Some variants change what "cost" means. Maximizing the probability of success along a path works the same way with a max-heap and multiplication. Minimizing the largest single step on a path keeps the maximum instead of the sum.
If weights can be negative, Dijkstra's algorithm can settle a node too early. Then you need Bellman-Ford, which is slower. If every edge has the same weight, plain BFS is simpler and faster.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue