🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Dijkstra's Algorithm — Shortest Path Step by Step — Complete Beginner Guide

Data Structures FoundationsDijkstra's Algorithm — Shortest Path Step by Step🟢 Free Lesson

Dijkstra's Algorithm — Shortest Path Step by Step — Complete Beginner Guide

Learning Objectives

  • State Dijkstra preconditions clearly
  • Relax edges with a priority queue
  • Track distances and parent pointers
  • Reconstruct the shortest path
  • Explain complexity and failure cases

What Problem Does Dijkstra Solve?

Dijkstra finds the shortest path from one source vertex to every other vertex in a graph with non-negative edge weights.

It is the classic tool for road maps, network latency, and game pathfinding.

RequirementRule
WeightsNon-negative only
SourceOne start vertex
OutputDistances and often parents
Graph typeDirected or undirected

If any edge weight is negative, use Bellman-Ford instead because Dijkstra can finalize the wrong distance.

Core Idea

Keep the best-known distance to every vertex. Always expand the unsettled vertex with the smallest tentative distance. When popped from a min-priority queue with non-negative weights, its distance is final.

Then relax each outgoing edge: if going through the current vertex is cheaper, update the neighbor.

Step-by-Step Walkthrough

Consider this weighted graph.

EdgeWeight
A to B4
A to C2
C to B1
B to D5
C to D8
D to E3
B to E10

Start from A with distance zero.

  1. Pop A with distance zero. Relax B to four and C to two.
  2. Pop C with distance two. Improve B from four to three through C.
  3. Pop B with distance three. Improve D to eight and E to thirteen.
  4. Pop D with distance eight. Improve E to eleven.
  5. Pop E with distance eleven. Nothing left to improve.

Final distances: A zero, B three, C two, D eight, E eleven.

Python Implementation

python
import heapq


def dijkstra(graph, start):
    dist = {start: 0}
    parent = {start: None}
    heap = [(0, start)]
    visited = set()

    while heap:
        d, node = heapq.heappop(heap)
        if node in visited:
            continue
        visited.add(node)
        for neighbor, weight in graph[node]:
            candidate = d + weight
            if neighbor not in dist or candidate < dist[neighbor]:
                dist[neighbor] = candidate
                parent[neighbor] = node
                heapq.heappush(heap, (candidate, neighbor))
    return dist, parent


graph = {
    "A": [("B", 4), ("C", 2)],
    "B": [("A", 4), ("C", 1), ("D", 5), ("E", 10)],
    "C": [("A", 2), ("B", 1), ("D", 8)],
    "D": [("B", 5), ("C", 8), ("E", 3)],
    "E": [("D", 3), ("B", 10)],
}

dist, parent = dijkstra(graph, "A")
print(dist)

Path Reconstruction

Parent pointers rebuild the route once distances are known.

python
def build_path(parent, target):
    path = []
    current = target
    while current is not None:
        path.append(current)
        current = parent[current]
    path.reverse()
    return path


print(build_path(parent, "E"))

Complexity

With a binary heap priority queue the standard bound is:

ComponentCost
Vertex extractionsO(V log V)
Edge relaxationsO(E log V)
Total with heapO of the quantity E plus V, times log V
SpaceO(V plus E)

A Fibonacci heap can improve theory to O of E plus V log V, but binary heaps dominate real code for simplicity.

Common Pitfalls

  • Negative weights break correctness
  • Forgetting to skip stale heap entries wastes work
  • Mixing directed and undirected edges changes results
  • Floating point weights can introduce tiny precision issues

Dijkstra versus BFS versus Bellman-Ford

AlgorithmWeightsCostNotes
BFSUnit onlyO(V plus E)Fewest hops
DijkstraNon-negativeO of E plus V times log VFast weighted
Bellman-FordAllows negativeO(V times E)Detects negative cycles

Dijkstra Dry Run Checklist

Before coding Dijkstra in an interview, dry run a five-node graph on paper. Maintain three tables: finalized flag, current best distance, and parent. At each pop, write the new distance only when the candidate improves the stored value. Cross out stale heap entries instead of trusting them blindly.

python
# Helper to relax one edge in a dry run table
def relax(dist, a, b, w):
    if a not in dist:
        return
    cand = dist[a] + w
    if b not in dist or cand < dist[b]:
        dist[b] = cand
        return True
    return False


dist = {"A": 0}
print(relax(dist, "A", "B", 4))  # True
print(dist)

Checklist before you claim correctness:

  1. Weights are non-negative
  2. Start distance is zero and others are unknown
  3. Pop skips already finalized vertices
  4. Relax uses strict improvement
  5. Parent updates only when distance improves

Run one negative-weight counterexample to explain why Bellman-Ford exists. Interviewers often probe that boundary next.

Key Takeaways

💡

  • Dijkstra requires non-negative edge weights
  • A min-priority queue always expands the closest unsettled vertex
  • Relaxation updates distance and parent when a cheaper route appears
  • Runtime with a binary heap is about O of E plus V times log V
  • Reconstruct paths by walking parent pointers backward

Practice Questions

  1. Run Dijkstra by hand on a five-vertex graph and list distances after each pop.
  2. Why does a negative edge break Dijkstra after a node is finalized?
  3. Compare when to choose BFS instead of Dijkstra for a map problem.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement