Dijkstra's Algorithm Code


#include 
using namespace std;
using PII = pair;

vector dijkstra(int n, vector>& graph, int start) {
    vector distances(n, INT_MAX);
    priority_queue, greater> pq;

    distances[start] = 0;
    pq.push({0, start});

    while (!pq.empty()) {
        int dist = pq.top().first;
        int node = pq.top().second;
        pq.pop();

        if (dist > distances[node]) continue;

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

            if (distances[node] + weight < distances[neighbor]) {
                distances[neighbor] = distances[node] + weight;
                pq.push({distances[neighbor], neighbor});
            }
        }
    }

    return distances;
}

void dij_3() {
    int n = 6;
    vector> graph(n);

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

    int start = 0;

    vector distances = dijkstra(n, graph, start);

    cout << "Shortest distances from node " << start << ":\n";
    for (int i = 0; i < n; ++i) {
        cout << "To node " << i << ": "
             << (distances[i] == INT_MAX ? -1 : distances[i]) << '\n';
    }
}