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

Bellman Ford Algorithm

Uploaded by

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

Bellman Ford Algorithm

Uploaded by

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

Bellman Ford Algorithm

01 December 2024 05:24 PM

GRAPH Page 1
IMPLEMENTATION :

vector<int> bellmanFord(int V, vector<vector<int>>& edges, int src) {

// Initially distance from source to all


// other vertices is not known(Infinite).

GRAPH Page 2
// other vertices is not known(Infinite).
vector<int> dist(V, 1e8);
dist[src] = 0;

// Relaxation of all the edges V times, not (V - 1) as we


// need one additional relaxation to detect negative cycle
for (int i = 0; i < V; i++) {
for (vector<int> edge : edges) {
int u = edge[0];
int v = edge[1];
int wt = edge[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v]) {

// If this is the Vth relaxation, then there is


// a negative cycle
if(i == V - 1)
return {-1};

// Update shortest distance to node v


dist[v] = dist[u] + wt;
}
}
}
return dist;
}

GRAPH Page 3

You might also like