[AlgoExpert] Dijkstr`s Algorithm

Dijkstra’s Algorithm

  • Time : O((v + e)log(v))
  • Space : O(v)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>
using namespace std;

vector<int> dijkstrasAlgorithm(int start, vector<vector<vector<int>>> edges) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> res(edges.size(), INT_MAX);
pq.push({0, start});

while(!pq.empty()) {
auto [c, u] = pq.top(); pq.pop();
if(c >= res[u]) continue;
res[u] = c;
for(auto& edge : edges[u]) {
int v = edge[0], w = edge[1];
if(res[v] > w + c)
pq.push({w + c, v});
}
}
for(auto& c : res)
if(c == INT_MAX) c = -1;
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/11/PS/AlgoExpert/dijkstra-algorithm/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.