AlgoPlus v0.1.0
Loading...
Searching...
No Matches
shortest_path.h
1#ifndef SHORTEST_PATH_H
2#define SHORTEST_PATH_H
3
4#ifdef __cplusplus
5#include <iostream>
6#include <limits>
7#include <queue>
8#include <unordered_map>
9#include <vector>
10#endif
11
22int shortest_path(std::unordered_map<int, std::vector<std::pair<int, int>>>& adj, int n, int start,
23 int end) {
24 std::vector<int> dist(n, std::numeric_limits<int>::max());
25
26 std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>,
27 std::greater<std::pair<int, int>>>
28 q;
29 q.push(std::make_pair(0, start));
30 dist[start] = 0;
31
32 while (!q.empty()) {
33 int currentNode = q.top().second;
34 int currentDist = q.top().first;
35 q.pop();
36
37 if (currentDist > dist[currentNode]) {
38 continue;
39 }
40 for (std::pair<int, int>& edge : adj[currentNode]) {
41 if (currentDist + edge.second < dist[edge.first]) {
42 dist[edge.first] = currentDist + edge.second;
43 q.push(std::make_pair(dist[edge.first], edge.first));
44 }
45 }
46 }
47
48 return (dist[end] != std::numeric_limits<int>::max()) ? dist[end] : -1;
49}
50
51#endif