Dijkstra Algorithm is a famous algorithm used to solve the single-source shortest path problem for a graph with non-negative edge weights. A graph consists of vertices (or nodes) connected by edges (or lines). In simple terms, it helps to find the quickest or least costly way from one point to another in a network, like finding the fastest route on a map.
The algorithm terminates when all nodes have been visited or the smallest tentative distance among the unvisited nodes is infinity, indicating that no path exists.
//dijkstra.cpp#include <iostream>#include <vector>using namespace std;vector<int> dijkstra(vector<vector<pair<int, int>>> adj, int src) {int size = adj.size();vector<bool> visited(size, false);vector<int> dist(size, INT_MAX);dist[src] = 0;while (true) { int node = -1; int mini = INT_MAX; for (int i = 0; i < size; i++) { if (!visited[i] && dist[i] < mini) { node = i; mini = dist[i]; } } if (node == -1) break; visited[node] = true; for (auto& neighbor : adj[node]) { int neighborNode = neighbor.first; int weight = neighbor.second; if (!visited[neighborNode] && dist[node] + weight < dist[neighborNode]) { dist[neighborNode] = dist[node] + weight; } }}return dist;}int main() {int n = 5;vector<vector<pair<int, int>>> adj(n);adj[0].push_back({1, 2});adj[0].push_back({2, 4});adj[1].push_back({2, 1});adj[1].push_back({3, 7});adj[2].push_back({4, 3});adj[3].push_back({4, 1});int src = 0;vector<int> distances = dijkstra(adj, src);cout << "Shortest distances from node " << src << ":\n";for (int i = 0; i < n; i++) { cout << "Node " << i << ": " << distances[i] << endl;}return 0;}
#dijkstra.pyimport heapqdef dijkstra(adj, src): size = len(adj) visited = [False] * size dist = [float('inf')] * size dist[src] = 0 while True: node = -1 mini = float('inf') for i in range(size): if not visited[i] and dist[i] < mini: node = i mini = dist[i] if node == -1: break visited[node] = True for neighbor, weight in adj[node]: if not visited[neighbor] and dist[node] + weight < dist[neighbor]: dist[neighbor] = dist[node] + weight return dist# Example usageif __name__ == "__main__": n = 5 adj = [[] for _ in range(n)] adj[0].append((1, 2)) adj[0].append((2, 4)) adj[1].append((2, 1)) adj[1].append((3, 7)) adj[2].append((4, 3)) adj[3].append((4, 1)) src = 0 distances = dijkstra(adj, src) print(f"Shortest distances from node {src}:") for i in range(n): print(f"Node {i}: {distances[i]}")
// dijkstra.jsfunction dijkstra(adj, src) { const size = adj.length; const visited = new Array(size).fill(false); const dist = new Array(size).fill(Infinity); dist[src] = 0; while (true) { let node = -1; let mini = Infinity; for (let i = 0; i < size; i++) { if (!visited[i] && dist[i] < mini) { node = i; mini = dist[i]; } } if (node === -1) break; visited[node] = true; for (const [neighbor, weight] of adj[node]) { if (!visited[neighbor] && dist[node] + weight < dist[neighbor]) { dist[neighbor] = dist[node] + weight; } } } return dist;}// Example usageconst n = 5;const adj = Array.from({ length: n }, () => []);adj[0].push([1, 2]);adj[0].push([2, 4]);adj[1].push([2, 1]);adj[1].push([3, 7]);adj[2].push([4, 3]);adj[3].push([4, 1]);const src = 0;const distances = dijkstra(adj, src);console.log(`Shortest distances from node ${src}:`);for (let i = 0; i < n; i++) { console.log(`Node ${i}: ${distances[i]}`);}
The initialization of the dist and visited arrays takes O(V).
Priority Queue Operations
For each node, we perform a pop operation from the priority queue, which takes O(logV)time.
For each neighbor of a node, we perform an insert operation (push) into the priority queue. In the worst case, this happens for every edge, so we can have at most E insertions, where E is the number of edges in the graph. Each insert operation also takes O(logV).
Time Complexity : O((V+E)logV)
where, V is the number of vertices. E is the number of edges.
Dijkstra picks the currently known shortest path and marks the node as finalized (i.e., it won't be updated again).
If a negative edge appears after a node is finalized, the algorithm does not revisit it, leading to incorrect results.
From the above example, we see that Dijkstra's Algorithm fails for negative edges. To overcome this limitation of Dijkstra's Algorithm, the Bellman-Ford Algorithm comes to the rescue.