0% found this document useful (0 votes)
16 views2 pages

Assignment 9

Uploaded by

riddhichaskar750
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Assignment 9

Uploaded by

riddhichaskar750
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <vector>
#include <queue>
#include <climits>

using namespace std;

vector<int> dijkstraHelper(vector<vector<pair<int, int>>> &adjacencyList, int


vertices, int source) {

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>


pq;

vector<int> distance(vertices, INT_MAX);

pq.push({0, source});
distance[source] = 0;

vector<bool> visited(vertices, false);

while (!pq.empty()) {
int u = pq.top().second;
pq.pop();

visited[u] = true;

for (auto &neighbor : adjacencyList[u]) {


int v = neighbor.first;
int weight = neighbor.second;

if (!visited[v] && distance[v] > distance[u] + weight) {


distance[v] = distance[u] + weight;
pq.push({distance[v], v});
}
}
}

return distance;
}
vector<int> dijkstra(vector<vector<int>> &edges, int vertices, int source) {

vector<vector<pair<int, int>>> adjacencyList(vertices);

for (int i = 0; i < (int)edges.size(); i++) {


adjacencyList[edges[i][0]].push_back({edges[i][1], edges[i][2]});
adjacencyList[edges[i][1]].push_back({edges[i][0], edges[i][2]});
}

return dijkstraHelper(adjacencyList, vertices, source);


}

int main() {
int vertices = 5;

vector<vector<int>> edges = {
{0, 1, 10},
{0, 2, 5},
{1, 2, 2},
{1, 3, 1},
{2, 3, 9},
{2, 4, 2},
{3, 4, 4}
};

int source = 0;

vector<int> distances = dijkstra(edges, vertices, source);

int sum = 0 ;
cout << "Shortest distances " << source << " to Destination:" << endl;
for (int i = 0; i < vertices; i++) {
cout << i << ": " << distances[i] << endl;
sum += distances[i];
}
cout<<"Shortest Path Distance is:-"<<sum<<endl;
return 0;
}

You might also like