Dijkstra's algorithm in python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Dijkstra's Algorithm is a famous graph-search algorithm that solves the single-source shortest path problem for a graph with non-negative edge weights, producing a shortest path tree. This algorithm is widely used in network routing protocols and geographic mapping services. In this article, we will explore Dijkstra's Algorithm in detail with a focus on its implementation in Python.
Concepts and Terminology
Before diving into the implementation, let's briefly cover some concepts and terms related to Dijkstra's Algorithm:
- Graph: A collection of nodes (vertices) connected by edges.
- Weighted Graph: A graph where each edge has a numerical value (weight) associated with it.
- Shortest Path: The path between two nodes that minimize the sum of the weights of the edges traversed.
- Priority Queue: A data structure that can efficiently remove the element with the highest (or lowest) priority.
Explanation and Approach
Dijkstra's Algorithm uses a priority queue to greedily select the next node to process based on the currently known shortest distance from the source node. Here’s a high-level overview of the algorithm:
- Initialization:
- Set the distance to the source node to `0` and all other nodes to infinity.
- Mark all nodes as unvisited.
- Use a priority queue to keep track of the nodes to be explored, initially containing only the source node with a distance of `0`.
- Processing:
- Extract the node `u` with the smallest distance from the priority queue, marking it as visited.
- For each unvisited neighbor `v` of `u`, calculate the tentative distance through `u`. If this distance is smaller than the currently known distance to `v`, update the distance and enqueue `v`.
- Termination:
- The algorithm terminates when all nodes have been visited.
Python Implementation
Below is the Python implementation of Dijkstra's Algorithm:
- A - B: 1
- A - C: 4
- B - C: 2
- B - D: 5
- C - D: 1
- A to A: 0
- A to B: 1
- A to C: 3
- A to D: 4
- Time Complexity:
- V: Number of vertices
- E: Number of edges
- This complexity arises due to the priority queue operations.
- Space Complexity:
- Storing distances for each vertex.

