Dijkstra’s Algorithm

Maryann Gitonga
2 min readSep 4, 2023

--

How it works

Imagine you’re planning a road trip using a navigation app. You start by entering your current location as the source and your destination as the goal, setting out on your journey. You begin at your current location (the source) and create a list of candidate routes. These routes represent various ways to reach your destination.

You use a priority queue which ensures that you consider the shortest or most efficient path first. This avoids wasting time and resources exploring longer routes when there’s a quicker way to your destination.

You begin by selecting the route with the shortest distance or quickest travel time from your list of candidates. Along the way, you might find alternative routes branching out. You evaluate these alternatives but prioritize the shortest ones, keeping track of them in your priority queue.

This process continues iteratively. When you reach your destination, you’ve not only found the fastest route but also ensured you didn’t miss any potentially quicker paths along the way. This is Dijkstra’s Algorithm.

The “relaxation” step of the algorithm uses a formular to update the minimum distance (or cost) to a vertex v if a shorter path to v through another vertex u is found.

Formula used at the relaxation step.
Illustration of the Dijkstra’s Algorithm

Benefits

  1. Optimized results: it ensures the discovery of the shortest path in a graph.
  2. Positive weights: it is suited for graphs with positive edge weights, making it ideal for scenarios involving costs or distances.
  3. Accurate results: it delivers precise results, particularly valuable in fields like transportation and logistics where accuracy is paramount.

Real-life application

When using a navigation app to find the quickest route, Dijkstra’s algorithm calculates the most efficient path in terms of distance or time.

Simple Code Illustration

Where next?

--

--

Maryann Gitonga

A Software Engineer who loves trying out different tooling & engineering concepts in Back-end Engineering & DevOps. An explorer in the ML world too!