Back to Home

Dijkstra's Algorithm

An algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks.

Visualization

Step 1 / 8
Speed:

Details

Analogy

Think of it like finding the fastest route on a GPS. The algorithm starts at your location. It explores the nearest intersections first. It keeps track of the 'shortest known time' to reach every intersection. As it discovers a new, quicker path to an intersection it already knew about, it updates its records. It continues spreading out, always prioritizing the overall closest intersection, until it has found the fastest route to your destination.

Purpose

To find the shortest path from a single source node to all other nodes in a weighted graph with non-negative edge weights.

Use Cases

Network routing protocols, GPS systems for finding the shortest path, flight planning, and link-state routing protocols.

Algorithm Steps

Line 1
1
initialize distances[all] = infinity
2
distances[start] = 0
3
create priority queue Q
4
add start to Q
5
while Q is not empty:
6
u = vertex with min distance in Q
7
remove u from Q
8
for each neighbor v of u:
9
alt = distances[u] + weight(u, v)
10
if alt < distances[v]:
11
distances[v] = alt
12
add v to Q
Current
Executed
Pending

Explanation

What's Happening?

Step 1/8

Start at node A. Distances: {B: 4, C: 2}. The next closest node is C.

Updates with each step • Clickfor full view

Code Implementation

import heapq

def dijkstra(graph, start_node):
    distances = {node: float('infinity') for node in graph}
    distances[start_node] = 0
    priority_queue = [(0, start_node)]
    previous_nodes = {node: None for node in graph}

    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)

        if current_distance > distances[current_node]:
            continue

        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                previous_nodes[neighbor] = current_node
                heapq.heappush(priority_queue, (distance, neighbor))
                
    return distances, previous_nodes
Dijkstra's Algorithm - Interactive Visualization | AlgoViz | AlgoViz