graph_theory/dijkstra.cpp
/*
    Implementation of Dijkstra's Algorithm.

    Arguments:
        - s: Source vertex in the graph.
        - v: Number of vertices in the graph.
        - d: Array of minimum distance to any given vertex. Defaults to INF if not reachable.
        - prev: Array of parents for every vertex. Defaults to -1 if it's not reachable.
        - al: Adjacency list representation of the graph. In the pair, it goes (vertex, cost).
*/
Implementation of Dijkstra's Algorithm.
Arguments:
s: Source vertex in the graph.
v: Number of vertices in the graph.
d: Array of minimum distance to any given vertex. Defaults to INF if not reachable.
prev: Array of parents for every vertex. Defaults to -1 if it's not reachable.
al: Adjacency list representation of the graph. In the pair, it goes (vertex, cost).
Implementation of Dijkstra ' s Algorithm . Arguments : s : Source vertex in the graph . v : Number of vertices in the graph . d : Array of minimum distance to any given vertex . Defaults to INF if not reachable . prev : Array of parents for every vertex . Defaults to - 1 if it ' s not reachable . al : Adjacency list representation of the graph . In the pair it goes ( vertex cost ) .
void dijkstra(T s, T v, vector<T>& d, vector<T>& prev, vector<vector<pair<T, T> > >& al) {
    priority_queue<pair<T, T>, vector<pair<T, T> >, comp> qu;
    vector<bool> marked(v, false);
    d.clear(); d.resize(v, INF);
    prev.clear(); prev.resize(v, -1);
    d[s] = 0;
    qu.push(make_pair(0, s));
    while (!qu.empty()) {
        pair<T, T> entry = qu.top(); qu.pop();
        T cur = entry.second;
        if (marked[cur]) continue;
        for (auto nbr : al[cur]) {
            if (marked[nbr.first]) continue;
            if (d[cur] + nbr.second < d[nbr.first]) {
                d[nbr.first] = d[cur] + nbr.second;
                prev[nbr.first] = cur;
                qu.push(make_pair(d[nbr.first], nbr.first));
            }
        }
        marked[cur] = true;
    }
}
void dijkstra ( T s , T v , vector < T > & d , vector < T > & prev , vector < vector < pair < T , T > > > & al ) { priority_queue < pair < T , T > , vector < pair < T , T > > , comp > qu ; vector < bool > marked ( v , false ) ; d . clear ( ) ; d . resize ( v , INF ) ; prev . clear ( ) ; prev . resize ( v , -1 ) ; d [ s ] = 0 ; qu . push ( make_pair ( 0 , s ) ) ; while ( ! qu . empty ( ) ) { pair < T , T > entry = qu . top ( ) ; qu . pop ( ) ; T cur = entry . second ; if ( marked [ cur ] ) continue ; for ( auto nbr : al [ cur ] ) { if ( marked [ nbr . first ] ) continue ; if ( d [ cur ] + nbr . second < d [ nbr . first ] ) { d [ nbr . first ] = d [ cur ] + nbr . second ; prev [ nbr . first ] = cur ; qu . push ( make_pair ( d [ nbr . first ] , nbr . first ) ) ; } } marked [ cur ] = true ; } }
Implementation of Dijkstra's Algorithm.
Implementation of Dijkstra ' s Algorithm .