MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / bellman_ford

Method bellman_ford

BellmanfordAlgorithm.java:11–42  ·  view source on GitHub ↗
(int V, ArrayList<ArrayList<Integer>> edges, int S)

Source from the content-addressed store, hash-verified

9*/
10class Solution {
11 static int[] bellman_ford(int V, ArrayList<ArrayList<Integer>> edges, int S) {
12 // Write your code here
13 int dist[] = new int[V];
14 Arrays.fill(dist,(int)1e8);
15 dist[S] = 0;
16 for(int i=0;i<V-1;i++){
17 boolean isChanged = false;
18 for(ArrayList<Integer> edge : edges){
19 int u = edge.get(0);
20 int v = edge.get(1);
21 int w = edge.get(2);
22 if(dist[u]!=(int)1e8 && dist[u] + w < dist[v]){
23 dist[v] = dist[u] + w;
24 isChanged=true;
25 }
26 }
27 if(!isChanged){
28 break; //if cur relation is not chaning any dist then no need to check further!
29 }
30 }
31
32 for(ArrayList<Integer> edge : edges){
33 int u = edge.get(0);
34 int v = edge.get(1);
35 int w = edge.get(2);
36 if(dist[u]!=(int)1e8 && dist[u] + w < dist[v]){
37 return new int[]{-1};
38 // dist[v] = dist[u] + w;
39 }
40 }
41 return dist;
42 }
43}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected