From 11e9850d03953852f49f032e5cbb76f062f558f7 Mon Sep 17 00:00:00 2001 From: Aayuiiitmg <03aayushshankar9b@gmail.com> Date: Thu, 4 Sep 2025 01:25:08 +0530 Subject: [PATCH] Fixes #583 Dijkstras algorithm implementation in C++ --- dijkstra.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 dijkstra.cpp diff --git a/dijkstra.cpp b/dijkstra.cpp new file mode 100644 index 00000000..824e0050 --- /dev/null +++ b/dijkstra.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; +class Edge{ + int v; + int wt; + public: + Edge(int v, int wt){ + this->v=v; + this->wt=wt; + } + void dijkstras(vector> &graph, int src) { + vector dist(graph.size(), INT_MAX); + dist[src] = 0; + priority_queue,vector>,greater>> pq; + pq.push({0,src}); + while(!pq.empty()){ + int u=pq.top().second; + pq.pop(); + vector edges=graph[u]; + for(auto edge: edges){ + if(dist[edge.v]>dist[u]+edge.wt) + { + dist[edge.v]=dist[u]+edge.wt; + pq.push({dist[edge.wt], edge.v}); + } + } + } + for(auto d: dist) + cout<> graph(6); + graph[0].push_back(Edge(1,2)); + graph[0].push_back(Edge(2,4)); + graph[1].push_back(Edge(2,1)); + graph[1].push_back(Edge(3,7)); + graph[2].push_back(Edge(4,3)); + graph[3].push_back(Edge(5,1)); + graph[4].push_back(Edge(5,5)); + graph[4].push_back(Edge(3,2)); + Edge e(0,0); + e.dijkstras(graph, 0); +} \ No newline at end of file