- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Dijkstra's Algorithm
Graphs
Dijkstra's Algorithm
BFS finds the fewest hops. Dijkstra finds the lowest cost. The moment your edges carry a weight - distance, price, latency - BFS starts giving confidently wrong answers.
Why BFS is not enough
BFS assumes every edge costs the same. With weights, a two-hop route can easily be cheaper than a one-hop route, and BFS will return the one-hop.
The idea
Always expand the cheapest node reached so far. Because you take the cheapest first, the first time you settle a node you have its final answer. That is BFS with a priority queue instead of a plain one.
Dijkstra
javascript
