|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + /* Function to implement Bellman-Ford Algorithm for an undirected graph |
| 4 | + * Parameters: |
| 5 | + * V: Number of vertices in the graph |
| 6 | + * edges: A vector of vectors where each sub-vector represents an edge in the format [source, destination, weight] |
| 7 | + * src: Source vertex from which shortest distances are calculated |
| 8 | + * Returns: |
| 9 | + * A vector of shortest distances from the source to all vertices. |
| 10 | + * If a negative-weight cycle is detected, returns [-1]. |
| 11 | + */ |
| 12 | + vector<int> bellmanFord(int V, vector<vector<int>>& edges, int src) { |
| 13 | + int n = 100000000; // Representing infinity |
| 14 | + vector<int> distance(V, n); // Distance array initialized to "infinity" |
| 15 | + distance[src] = 0; // Distance to the source vertex is 0 |
| 16 | + |
| 17 | + // Step 1: Preprocess the edges to handle the undirected graph |
| 18 | + vector<vector<int>> undirectedEdges; |
| 19 | + for (auto edge : edges) { |
| 20 | + // Add both directions for the undirected graph |
| 21 | + undirectedEdges.push_back({edge[0], edge[1], edge[2]}); // (u -> v) |
| 22 | + undirectedEdges.push_back({edge[1], edge[0], edge[2]}); // (v -> u) |
| 23 | + } |
| 24 | + |
| 25 | + // Step 2: Relax all edges (V-1) times |
| 26 | + for (int i = 0; i < V - 1; i++) { |
| 27 | + for (auto edge : undirectedEdges) { |
| 28 | + int source = edge[0]; |
| 29 | + int destination = edge[1]; |
| 30 | + int weight = edge[2]; |
| 31 | + |
| 32 | + // Relax the edge if the source distance is not infinity and the new path is shorter |
| 33 | + if (distance[source] != n && (distance[source] + weight < distance[destination])) { |
| 34 | + distance[destination] = distance[source] + weight; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + // Step 3: Check for negative-weight cycles |
| 40 | + for (auto edge : undirectedEdges) { |
| 41 | + int source = edge[0]; |
| 42 | + int destination = edge[1]; |
| 43 | + int weight = edge[2]; |
| 44 | + |
| 45 | + // If the edge can still be relaxed, a negative-weight cycle exists |
| 46 | + if (distance[source] != n && (distance[source] + weight < distance[destination])) { |
| 47 | + return vector<int>(1, -1); // Return [-1] to indicate a negative-weight cycle |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // Step 4: Return the calculated shortest distances from the source vertex |
| 52 | + return distance; |
| 53 | + } |
| 54 | +}; |
0 commit comments