Bellman_ford algo

PHOTO EMBED

Thu Jun 13 2024 14:06:35 GMT+0000 (Coordinated Universal Time)

Saved by @divay6677 ##c++

vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
       vector<int> dis(V,1e8);
       dis[S] = 0;
       for(int cnt = 0; cnt<=V-1; cnt++){
           for(auto edge : edges){
               int u = edge[0];
               int v = edge[1];
               int w = edge[2];
               if(dis[u] != 1e8 and dis[u] + w < dis[v]){
                   dis[v] = dis[u] + w;
               }
           }
       }
       
       // Check for negative weight cycles
       for(auto edge : edges) {
           int u = edge[0];
           int v = edge[1];
           int w = edge[2];
           if(dis[u] != 1e8 && dis[u] + w < dis[v]) {
               // If we can still relax an edge, there is a negative weight cycle
               return {-1}; // Return an empty vector to indicate the presence of a negative cycle
           }
       }
       
       return dis;
    }
content_copyCOPY

To find the shorted dis in case of the -ve edges and this code is capable of determing the -ve cycle