|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + /* Function to implement Bellman-Ford Algorithm |
| 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 | + // Step 1: Initialize the distances to all vertices as a very large number (infinity) |
| 14 | + // Use 100000000 as the value for "infinity" as per the problem constraints |
| 15 | + int n = 100000000; |
| 16 | + vector<int> distance(V, n); // Distance array initialized to "infinity" |
| 17 | + distance[src] = 0; // Distance to the source vertex is 0 |
| 18 | + |
| 19 | + // Step 2: Relax all edges (V-1) times |
| 20 | + // Iterate (V-1) times because the shortest path in a graph with V vertices can have at most (V-1) edges |
| 21 | + for (int i = 0; i < V - 1; i++) { |
| 22 | + // Traverse through all edges |
| 23 | + for (auto edge : edges) { |
| 24 | + int source = edge[0]; // Source vertex of the edge |
| 25 | + int destination = edge[1]; // Destination vertex of the edge |
| 26 | + int weight = edge[2]; // Weight of the edge |
| 27 | + |
| 28 | + // Relax the edge if the source distance is not infinity and the new path is shorter |
| 29 | + if (distance[source] != n && (distance[source] + weight < distance[destination])) { |
| 30 | + distance[destination] = distance[source] + weight; // Update the shortest distance |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // Step 3: Check for negative-weight cycles |
| 36 | + // A negative-weight cycle exists if we can still relax any edge after (V-1) iterations |
| 37 | + for (auto edge : edges) { |
| 38 | + int source = edge[0]; // Source vertex of the edge |
| 39 | + int destination = edge[1]; // Destination vertex of the edge |
| 40 | + int weight = edge[2]; // Weight of the edge |
| 41 | + |
| 42 | + // If the edge can still be relaxed, a negative-weight cycle exists |
| 43 | + if (distance[source] != n && (distance[source] + weight < distance[destination])) { |
| 44 | + return vector<int>(1, -1); // Return [-1] to indicate a negative-weight cycle |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Step 4: Return the calculated shortest distances from the source vertex |
| 49 | + return distance; |
| 50 | + } |
| 51 | +}; |
0 commit comments