-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstrasAlgorithm.cpp
More file actions
102 lines (87 loc) · 1.83 KB
/
DijkstrasAlgorithm.cpp
File metadata and controls
102 lines (87 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <vector>
#include <queue>
class HeapNode
{
public:
int vertex;
int weight;
bool operator()(const HeapNode& a, const HeapNode& b) const
{
return a.weight > b.weight;
}
};
class Edge
{
public:
int src;
int dest;
int weight;
};
class DirectedGraph
{
private:
std::vector<std::vector<Edge>> adj;
int nodes;
private:
void print(int curr, const std::vector<int>& parent)
{
if (curr == -1)
{
return;
}
print(parent[curr], parent);
std::cout << curr << " -> ";
}
public:
DirectedGraph(int num, const std::vector<Edge>& edges)
: nodes(num)
{
adj.resize(nodes);
for (auto iter : edges)
{
adj[iter.src].push_back(iter);
}
}
void dijkstra(int src)
{
std::vector<bool> visited(nodes, false);
std::vector<int> dist(nodes, std::numeric_limits<int>::max());
std::vector<int> parent(nodes, -1);
std::priority_queue<HeapNode, std::vector<HeapNode>, HeapNode> pq;
pq.push({0, 0});
visited[0] = true;
parent[0] = -1;
while (!pq.empty())
{
HeapNode top = pq.top();
int dist_from_start = top.weight;
pq.pop();
for (const auto& iter : adj[top.vertex])
{
int neighb = iter.dest;
int distance = iter.weight;
if (!visited[neighb] && ((dist_from_start + distance) < dist[neighb]))
{
dist[neighb] = dist_from_start + distance;
parent[neighb] = top.vertex;
pq.push({neighb, dist[neighb]});
}
}
visited[top.vertex] = true;
}
for (int i = 1; i < nodes; ++i) {
std::cout << "Path from 0 to " << i << " has a cost of " << dist[i] << " and the route is ";
print(i, parent);
std::cout << std::endl;
}
}
};
int main()
{
std::vector<Edge> edges{ {0, 1, 10}, {0, 4, 3}, {1, 2, 2}, {1, 4, 4}, {2, 3, 9}, {3, 2, 7}, {4, 1, 1}, {4, 2, 8}, {4, 3, 2} };
int N = 5;
DirectedGraph obj(N, edges);
obj.dijkstra(0);
return 0;
}