All examples

Examples

Dijkstra’s shortest paths in Java

A weighted graph of six nodes: the priority queue, the distances and the Java code move together until every shortest distance from node 0 is settled.

This video was made with the Algorithm visuals skill.

  • 1:04
  • Algorithm visuals
  • Narrated by Kore
  • English

Made from a prompt

Dijkstra’s shortest paths from node 0 on a small weighted graph, in Java

Video transcript

How can you find the shortest distances from node 0?

This weighted graph is our input. Settled distances stay final. Orange marks executing code; green marks settled nodes.

Line 4 sets dist to 0. Line 14 finds shorter routes: 4 to 1, 1 to 2. Which node comes next?

Node 2 wins with distance 1. Through it, 1 improves to 3.

Node 1 improves dist to 8. Line 11 skips its outdated distance 4.

Node 3 reaches 5 at 14; equal or longer routes change nothing. Node 4 settles.

Now 11 + 2 beats 14, so dist becomes 13.

Node 5 settles; outdated 14 is skipped. The queue empties.

From 0, final distances are 0, 3, 1, 8, 11, 13. Dijkstra needs nonnegative weights.

Your topic, drawn in about a minute.

Your first 2 videos are free, up to 1 minute each, watermarked. No card required. Full product, every voice and style included.