shriyanshi24jindal

Bellman-Ford

Mar 30th, 2026
104
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 11.06 KB | None | 0 0
  1. // User function Template for Java
  2. class iPair
  3. {
  4. int vertex;
  5. int weight;
  6. iPair(int vertex, int weight)
  7. {
  8. this.vertex = vertex;
  9. this.weight = weight;
  10. }
  11. }
  12.  
  13. class Pair
  14. {
  15. int node;
  16. int dist;
  17. Pair(int node, int dist)
  18. {
  19. this.node = node;
  20. this.dist = dist;
  21. }
  22. }
  23.  
  24. class Solution {
  25. // Diff: In dijkstra we do not have cycle in weighted, undirected, connected graph but here we can have cycle
  26.  
  27. /**
  28.   * Idea
  29.   * 1. Create a distance array and assign values as (int)1e8
  30.   * 2. Relax the edges N-1 times
  31.   * 3. Now relax the edges again and see if you if relaxation is possible
  32.   * - if possible then we have negative cycle, return array of -1 element
  33.   * - else keep continuing
  34.   * 4. At last return distance array
  35.   */
  36. public int[] bellmanFord(int V, int[][] edges, int src) {
  37. // Step-1 create a distance array
  38. int[] distance = new int[V];
  39. Arrays.fill(distance, (int)1e8);
  40. distance[src] = 0;
  41.  
  42.  
  43. // Step-2 Relax edges V-1 times
  44. for(int i=0; i<V-1; i++)
  45. {
  46. for(int[] edge : edges)
  47. {
  48. int u = edge[0];
  49. int v = edge[1];
  50. int w = edge[2];
  51.  
  52. if(distance[u] != (int)1e8 && distance[v] > distance[u] + w)
  53. {
  54. distance[v] = distance[u] + w;
  55. }
  56. }
  57. }
  58.  
  59. // Step-3 to detect negative cycle
  60. for(int[] edge : edges)
  61. {
  62. int u = edge[0];
  63. int v = edge[1];
  64. int w = edge[2];
  65.  
  66. if(distance[u] != (int)1e8 && distance[v] > distance[u] + w)
  67. {
  68. return new int[]{-1};
  69. }
  70. }
  71. return distance;
  72. }
  73. }
RAW Paste Data Copied