Dijkstra’s Algorithm

Algorithm Description

Dijkstra’s algorithm is used to find the shortest paths from a source vertex to all other vertices in a weighted graph with non-negative weights. It uses a priority queue to always expand the shortest known path until all vertices have been processed, ensuring an efficient O((V + E) log V) time complexity in typical cases.

C++ Code

#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;

#define INF numeric_limits<int>::max()
#define V 6

vector<int> dijkstra(vector<vector<pair<int, int>>>& graph, int source) {
    vector<int> dist(V, INF);
    dist[source] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, source});

    while (!pq.empty()) {
        int u = pq.top().second;
        int d = pq.top().first;
        pq.pop();

        if (d > dist[u]) continue;

        for (auto& edge : graph[u]) {
            int v = edge.first;
            int weight = edge.second;

            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }

    return dist;
}

int main() {
    vector<vector<pair<int, int>>> graph(V);

    graph[0].push_back({1, 4});
    graph[0].push_back({2, 1});
    graph[1].push_back({3, 1});
    graph[2].push_back({1, 2});
    graph[2].push_back({3, 5});
    graph[3].push_back({4, 3});
    graph[4].push_back({5, 2});
    graph[5].push_back({3, 1});

    int source = 0;
    vector<int> distances = dijkstra(graph, source);

    cout << "Shortest distances from source vertex " << source << ":\n";
    for (int i = 0; i < V; ++i) {
        cout << "Vertex " << i << ": " << distances[i] << "\n";
    }

    return 0;
}

Time and Space Complexity

Operation Time Complexity Space Complexity
Initialization O(V) O(V + E)
Dijkstra’s Algorithm O((V + E) log V) O(V)

Where:

  • V: Number of vertices in the graph.
  • E: Number of edges in the graph.

← Back to Homepage