DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸ›€οΈ Dijkstra's Algorithm Explained Like You're 5

Finding the shortest path

Day 106 of 149

πŸ‘‰ Full deep-dive with code examples


The GPS Navigation Analogy

When you ask Google Maps for directions:

  • It doesn't try every possible route
  • It smartly finds the shortest path
  • Considers traffic, distance, time

Dijkstra's Algorithm is like the GPS in your phone!

It finds the shortest path between two points in a network.


The Problem It Solves

Finding a good route in a network:

  • Cities connected by roads β†’ Which route is shortest?
  • Computer networks β†’ Which path has lowest delay?
  • Social networks β†’ Who's the closest connection?

You can't just pick the closest next stepβ€”sometimes a longer first step leads to a shorter total path!


How It Works

Imagine you're at a city and want to reach another:

  1. Start at your location (distance = 0)
  2. Look at all connected cities (note their distances)
  3. Pick the closest unvisited city
  4. Update distances to its neighbors (if shorter than before)
  5. Repeat until you reach the destination

Think of it like exploring a maze, but expanding from the closest point first.


A Simple Example

City A β†’ B (4 km) β†’ D (7 km)
    ↓         β†˜
   (1 km)     (2 km)
    ↓           β†˜
   C ──────────→ D (4 km)

Shortest A to D:
A β†’ C (1 km) β†’ D (4 km) = 5 km βœ“
NOT:
A β†’ B (4 km) β†’ D (2 km) = 6 km
Enter fullscreen mode Exit fullscreen mode

Where It's Used

  • Navigation apps (Google Maps, Waze)
  • Network routing (internet packets)
  • Game AI (finding paths for characters)
  • Airline route planning

In One Sentence

Dijkstra's Algorithm finds the shortest path between two points by repeatedly expanding from the nearest unvisited location.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)