DSA
    advanced

    Dijkstra's Algorithm

    Software Engineer path · lesson 23 of 99
    time O((V+E) log V)
    space O(V)
    Maze:
    Tap or drag on the grid to
    Algorithm

    Switch and compare the expanded-cells count.

    Show costs (g)
    ~5~5~5~5~5~5~5~5~5~5~5~5~5S~5~5~5~5~5G~5~5~5~5~5~5~5~5~5~5~5~5~5
    ExpandingFrontierExpandedNeighbour checkedShortest path

    Start at (4,1), goal (4,11).

    Code (running line highlighted)
    1. 1dist[start] = 0; pq = [(0, start)]
    2. 2while pq:
    3. 3 d, cell = pq.pop_min() # cheapest first
    4. 4 if cell == goal: return path
    5. 5 for nb in neighbours(cell):
    6. 6 if d + cost(nb) < dist[nb]: dist[nb] = d + cost(nb); parent[nb] = cell; pq.push(nb)
    7. 7return "no path"
    Cells expanded
    0 / 105
    Frontier pushes
    1 / 117
    Invariant: Every expanded cell already has its final, cheapest distance.

    Tap any element in the diagram to inspect its state at this step.

    1 / 223

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Settle the closest node

    Sequence

    Order one iteration of Dijkstra’s algorithm with a priority queue.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What happens if edge weights are negative?

    When to reach for this

    • Shortest Path in a **Weighted Graph** (non-negative weights)
    • Network Routing Protocols (e.g., OSPF)
    • Finding the cheapest cost to reach a destination

    Interview Questions

    Uber
    Lyft
    Meta
    Google
    Amazon
    Microsoft
    Bloomberg
    Airbnb
    LinkedIn
    Meta
    Bloomberg
    Microsoft
    Google
    Amazon
    Netflix

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required