-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathDijkstra.cpp
More file actions
84 lines (62 loc) · 2.11 KB
/
Dijkstra.cpp
File metadata and controls
84 lines (62 loc) · 2.11 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
// Dijkstra's algorithm is a widely used algorithm for finding the shortest path from a single source vertex to all other vertices in a weighted graph. It's particularly useful for graphs with non-negative edge weights.
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int INF = INT_MAX;
// Define a class to represent a weighted graph
class Graph {
public:
int V; // Number of vertices
vector<vector<pair<int, int>>> adj; // Adjacency list
Graph(int vertices) {
V = vertices;
adj.resize(V);
}
// Function to add an edge to the graph
void addEdge(int u, int v, int w) {
adj[u].push_back({v, w});
adj[v].push_back({u, w}); // If the graph is undirected
}
// Dijkstra's algorithm to find the shortest path
vector<int> dijkstra(int src) {
vector<int> dist(V, INF);
dist[src] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, src});
while (!pq.empty()) {
int u = pq.top().second;
int weight = pq.top().first;
pq.pop();
if (weight > dist[u]) continue;
for (pair<int, int>& edge : adj[u]) {
int v = edge.first;
int w = edge.second;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
};
int main() {
int V, E; // Number of vertices and edges
cin >> V >> E;
Graph g(V);
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
int src; // Source vertex for Dijkstra's algorithm
cin >> src;
vector<int> shortestDistances = g.dijkstra(src);
cout << "Shortest distances from vertex " << src << ":\n";
for (int i = 0; i < V; i++) {
cout << "Vertex " << i << ": " << shortestDistances[i] << "\n";
}
return 0;
}