Graphs11/11/2025

Dijkstra's Algorithm: Finding the Shortest Path

Dijkstra's Algorithm: Finding the Shortest Path

Dijkstra's algorithm is one of the most famous algorithms in computer science. It is used to find the shortest path between nodes in a weighted graph.

The algorithm is widely used in real-world systems such as GPS navigation, network routing, and logistics optimization.

The Problem It Solves

In many situations we need to find the cheapest route between two points in a network. Each edge in the graph has a cost or distance.

Dijkstra's algorithm calculates the minimum distance from a starting node to every other node in the graph.

Core Idea

The algorithm repeatedly selects the closest unvisited node and updates the distances of its neighbors.

  1. Assign distance 0 to the starting node
  2. Assign infinity to all other nodes
  3. Pick the node with the smallest distance
  4. Update distances of its neighbors
  5. Repeat until all nodes are processed

JavaScript Implementation

function dijkstra(graph, start) {
  const distances = {};
  const visited = new Set();

  for (const node in graph) {
    distances[node] = Infinity;
  }

  distances[start] = 0;

  while (true) {
    let closestNode = null;

    for (const node in distances) {
      if (!visited.has(node) &&
          (closestNode === null || distances[node] < distances[closestNode])) {
        closestNode = node;
      }
    }

    if (closestNode === null) break;

    visited.add(closestNode);

    for (const neighbor in graph[closestNode]) {
      const newDist = distances[closestNode] + graph[closestNode][neighbor];

      if (newDist < distances[neighbor]) {
        distances[neighbor] = newDist;
      }
    }
  }

  return distances;
}

Time Complexity

The time complexity depends on the data structure used. With a priority queue, the complexity becomes O((V + E) log V).

Applications

  • GPS navigation systems
  • Internet routing protocols
  • Game pathfinding
  • Transportation networks

Conclusion

Dijkstra's algorithm remains one of the most important shortest-path algorithms. Its efficiency and reliability make it a fundamental tool in both theoretical and practical computing.

Practice the Concept

The best way to understand an algorithm is by interacting with it. Try the simulator below.

Test Your Knowledge

Ready to check what you've learned? Take the quiz below and challenge yourself.

Dijkstra Algorithm Quiz

Check your knowledge of shortest path algorithms.