(int V, ArrayList<ArrayList<Integer>> edges, int S)
| 9 | */ |
| 10 | class 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 | } |
nothing calls this directly
no outgoing calls
no test coverage detected