forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
djikstra-algoriths.cpp
76 lines (60 loc) · 1.8 KB
/
djikstra-algoriths.cpp
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
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
class Graph {
public:
Graph(int vertices);
void addEdge(int u, int v, int weight);
void dijkstra(int source);
private:
int vertices;
vector<vector<pair<int, int>>> adjacencyList; // Pair: (neighbor, edge weight)
};
Graph::Graph(int vertices) {
this->vertices = vertices;
adjacencyList.resize(vertices);
}
void Graph::addEdge(int u, int v, int weight) {
adjacencyList[u].push_back(make_pair(v, weight));
adjacencyList[v].push_back(make_pair(u, weight)); // For undirected graph
}
void Graph::dijkstra(int source) {
vector<int> distance(vertices, INF);
distance[source] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, source));
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (const auto& neighbor : adjacencyList[u]) {
int v = neighbor.first;
int weight = neighbor.second;
if (distance[u] + weight < distance[v]) {
distance[v] = distance[u] + weight;
pq.push(make_pair(distance[v], v));
}
}
}
cout << "Shortest distances from source " << source << " to all other vertices:\n";
for (int i = 0; i < vertices; ++i) {
cout << "Vertex " << i << ": " << distance[i] << endl;
}
}
int main() {
int vertices = 6;
Graph graph(vertices);
graph.addEdge(0, 1, 2);
graph.addEdge(0, 2, 4);
graph.addEdge(1, 2, 1);
graph.addEdge(1, 3, 7);
graph.addEdge(2, 4, 3);
graph.addEdge(3, 4, 1);
graph.addEdge(3, 5, 5);
graph.addEdge(4, 5, 2);
int source = 0;
graph.dijkstra(source);
return 0;
}