Question: ( I am getting Vertex 0 and 1 wrong for Vertex 0 i need to ger 4 and Vertex 1 i need to get 3

(I am getting Vertex 0 and 1 wrong for Vertex 0 i need to ger 4 and Vertex 1 i need to get 3 but for both of thoses vertexes i keep getting no path) This is my code below: #include
#include
#include
#include
using namespace std;
vector dijkstra(int V, vector>> adj, int S, vector& dist){
dist.resize(V, INT_MAX); // dist[i] will hold the shortest distance from S to i
vector prev(V,-1); // prev[i] will hold the penultimate vertex in the shortest path from S to i
// Priority queue to store vertices that are being processed
priority_queue, vector>, greater>> pq;
// Initialize source vertex distance as 0 and push it to the priority queue
dist[S]=0; // Adjusted: Set distance from source to itself as 0
pq.push({0, S});
// Dijkstra's algorithm
while (!pq.empty()){
int u = pq.top().second;
pq.pop();
// Visit each neighbor of u
for (auto& edge : adj[u]){
int v = edge.first; // neighbor vertex
int weight = edge.second; // weight of the edge from u to v
// If a shorter path is found, update distance and penultimate vertex
if (dist[u]+ weight < dist[v]){
dist[v]= dist[u]+ weight;
prev[v]= u;
pq.push({dist[v], v});
}
}
}
return prev; // Return the penultimate vertex array
}
int main(){
int v, e, source;
cout << "Enter the number of vertices and edges: ";
cin >> v >> e;
// Initialize the graph with n vertices
vector>> adj(v);
// Read edges and weights
cout << "Enter edges in the format (from to weight):"<< endl;
for (int i =0; i < e; ++i){
int from, to, weight;
cin >> from >> to >> weight;
adj[from].push_back({to, weight});
}
cout << "Enter the source vertex: ";
cin >> source;
// Find shortest paths from source to all vertices
vector dist;
vector prev_vertices = dijkstra(v, adj, source, dist);
// Print shortest paths
cout << "Shortest paths from source vertex "<< source <<":
";
for (int i =0; i < v; ++i){
cout << "Vertex "<< i <<": ";
if (dist[i]== INT_MAX){
cout <<"No path
";
} else {
cout << dist[i]<< endl;
}
}
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!