Lesson 27/30

Tutorials DSA Mastery

Dijkstra's Algorithm: Shortest path in weighted graphs

On this page

Dijkstra's Algorithm

BFS finds the shortest path in unweighted graphs. But what if connections have different costs (e.g., distance or traffic)? Dijkstra's Algorithm is the world's most famous solution for finding the shortest path in Weighted Graphs.

1. How it Works (Greedy + DP)

Dijkstra uses a Priority Queue (Min-Heap).

  1. Set distance to all nodes to Infinity (except Start = 0).
  2. Pick the unvisited node with the smallest distance.
  3. For each neighbor, calculate NewDistance = CurrentDistance + EdgeWeight.
  4. If NewDistance < ExistingDistance, update the neighbor and add it to the Priority Queue.

2. The "No Negative Weights" Rule

Dijkstra is a greedy algorithm. It assumes that once it "relaxes" a node, it has found the absolute shortest path. This only works if all edge weights are positive. If you have negative weights (e.g., a "Cashback" on a path), you must use the Bellman-Ford algorithm instead.

4. Interview Mastery

Q: "Where is Dijkstra used in modern software architecture?"

Architect Answer: "It is the heart of **OSPF (Open Shortest Path First)** routing protocols that power the internet. It is also used by **Google Maps** (though with more advanced heuristics like A*) to find the fastest route between two cities. In microservices, it can be used for 'Service Discovery' to find the instance with the lowest latency."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

DSA Mastery
Course syllabus
1. Algorithmic Foundations
2. Linear Data Structures
3. Non-Linear Data Structures
4. Searching & Sorting
5. Algorithmic Patterns
6. Dynamic Programming (DP)
7. Advanced Graphs & Interview
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details