Skip to content

Commit 04dd9e7

Browse files
authored
Add Dijkstra's shortest path algorithm. (#21)
1 parent 62afc11 commit 04dd9e7

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

graph/c++/dijkstra.cpp

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
6+
class DirectedGraph
7+
{
8+
typedef vector< vector < pair<int, long long> > > AdjList;
9+
10+
int V; // Number of vertices
11+
12+
AdjList adjList;
13+
public:
14+
DirectedGraph(int V);
15+
16+
void addEdge(int u, int v, long long w);
17+
18+
// Finds the shortest path from source to destination
19+
long long shortestPathDijkstra(int source, int destination, vector<int>& path);
20+
};
21+
22+
DirectedGraph::DirectedGraph(int n) : adjList(n), V(n)
23+
{
24+
}
25+
26+
void DirectedGraph::addEdge(int u, int v, long long w)
27+
{
28+
adjList[u].emplace_back(v, w);
29+
}
30+
31+
long long DirectedGraph::shortestPathDijkstra(int source, int destination, vector<int>& path)
32+
{
33+
vector< int > parent(V, -1);
34+
vector< long long > minCost(V, LLONG_MAX);
35+
set< pair<long long, int> > pq;
36+
37+
minCost[source] = 0LL;
38+
pq.insert( make_pair(0LL, source) );
39+
40+
while(!pq.empty())
41+
{
42+
set< pair<long long, int> >::iterator it = pq.begin();
43+
int u = it->second;
44+
pq.erase(it);
45+
46+
if(u == destination)
47+
break;
48+
49+
for(int i=0; i < adjList[u].size(); ++i)
50+
{
51+
int v = adjList[u][i].first;
52+
long long w = adjList[u][i].second;
53+
if(minCost[v] > minCost[u] + w)
54+
{
55+
pq.erase( make_pair(minCost[v], v) );
56+
minCost[v] = minCost[u] + w;
57+
pq.insert( make_pair(minCost[v], v) );
58+
parent[v] = u;
59+
}
60+
}
61+
}
62+
63+
int tmp = destination;
64+
while(tmp != -1)
65+
{
66+
path.push_back(tmp);
67+
tmp = parent[tmp];
68+
}
69+
reverse(path.begin(), path.end());
70+
71+
return minCost[destination];
72+
}
73+
74+
// Driver program to test methods of graph class
75+
int main()
76+
{
77+
// Create a graph given in the above diagram
78+
DirectedGraph g(5);
79+
g.addEdge(0, 1, 3LL);
80+
g.addEdge(1, 3, 6LL);
81+
g.addEdge(3, 4, 2LL);
82+
g.addEdge(1, 2, 4LL);
83+
g.addEdge(2, 3, 1LL);
84+
85+
vector<int> path;
86+
long long cost = g.shortestPathDijkstra(0, 4, path);
87+
cout << "Shortest path from vertex 0 to vertex 4 costs " << cost << " and follows the vertices:" << endl;
88+
for(int i = 0; i < path.size(); ++i)
89+
{
90+
cout << path[i] << endl;
91+
}
92+
93+
return 0;
94+
}

0 commit comments

Comments
 (0)