0% found this document useful (0 votes)
34 views3 pages

Dijsktras

Uploaded by

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

Dijsktras

Uploaded by

sv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

#include <vector>
#include <queue>
#include <limits>

using namespace std;

// Define a pair to store {distance, node}


typedef pair<int, int> pii;

class Graph {
int V; // Number of vertices
vector<vector<pii>> adj; // Adjacency list representation

public:
Graph(int vertices) {
V = vertices;
adj.resize(V);
}

void addEdge(int u, int v, int weight) {


adj[u].push_back({weight, v});
// adj[v].push_back({weight, u}); // Remove this for a directed graph
}

void dijkstra(int src) {


vector<int> dist(V, numeric_limits<int>::max()); // Distance array
priority_queue<pii, vector<pii>, greater<pii>> pq; // Min-heap

// Initialize source
dist[src] = 0;
pq.push({0, src});

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

// Ignore outdated distances


if (d > dist[u]) continue;

for (auto edge : adj[u]) {


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

// Relaxation step
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}

// Print the shortest distances


cout << "Vertex Distance from Source " << src << ":\n";
for (int i = 0; i < V; i++)
cout << "Vertex " << i << " -> Distance: " << dist[i] << endl;
}
};

int main() {
int V = 5; // Number of vertices
Graph g(V);

// Adding edges (undirected graph)


g.addEdge(0, 1, 10);
g.addEdge(0, 4, 3);
g.addEdge(1, 2, 2);
g.addEdge(1, 4, 4);
g.addEdge(2, 3, 9);
g.addEdge(3, 4, 7);
g.addEdge(4, 2, 1);

int source = 0; // Starting vertex


g.dijkstra(source);

return 0;
}

You might also like