Dijkstra's Algorithm

Find the shortest path from a starting node to every other node in a graph where edges have non-negative weights.

Dijkstra's Algorithm Practice Problems

Medium

4 problems
  1. 90

    Network Delay Time

    Find how long it takes for a signal to reach every node in a weighted network.

    medium
  2. 91

    Path with Maximum Probability

    Find the path between two nodes with the highest combined success probability.

    medium
  3. 245

    Number of Ways to Arrive at Destination

    Count the number of fastest routes between two intersections.

    medium
  4. 246

    Path with Minimum Effort

    Find the route across a grid that minimizes its single worst elevation change.

    medium

Hard

1 problems
  1. 92

    Swim in Rising Water

    Find the earliest time you can swim from the top-left to the bottom-right of a rising-water grid.

    hard

How to practise Dijkstra

Spotting one

Something travels out from a starting point and you want the cheapest, shortest or fastest way to reach somewhere else. Every step has a cost and no cost is negative.

Cost is doing a lot of work in that sentence. It is often time, money, distance or risk.

Do you even need it?

If every step costs the same, you do not. Plain breadth-first search is simpler and quicker.

If any step can cost a negative amount, Dijkstra is wrong and will hand you a confident wrong answer. Use Bellman-Ford.

Where to start

Network Delay Time. Ordinary network, ordinary costs, and the question is just how long until the last point hears the signal.

Then Path with Minimum Effort, which quietly changes the rules. The cost of a route is not the sum of its steps, it is the single worst step in it. The method does not change at all. Only what you mean by cost so far changes, and once that clicks a whole family of problems opens up.

Path with Maximum Probability changes them again: costs multiply instead of adding, and you want the biggest result rather than the smallest.

Number of Ways to Arrive at Destination asks you to count cheapest routes as well as find one. Swim in Rising Water is the hardest here and puts the worst step idea on a grid.

Common mistakes

Using it when a cost can be negative. Easily the most common misuse.

Finalising a point and then updating it again later. Once Dijkstra settles a point it is settled, and reprocessing it means something else is wrong.

Scanning the whole list each round to find the nearest unvisited point. It works. It is also what makes a fast method slow. The priority queue is the point.