-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBellmanFordAlgo.java
35 lines (31 loc) · 996 Bytes
/
BellmanFordAlgo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.*;
public class Solution {
static int bellmonFord(int vertices, int n, int src, int dest, ArrayList<ArrayList<Integer>> edges) {
int[] result = new int[vertices+1];
Arrays.fill(result,1000000000);
result[src] = 0;
for(int i=1;i<=vertices-1;i++){
for(ArrayList<Integer> x : edges){
if(x.get(2) + result[x.get(0)] < result[x.get(1)]){
result[x.get(1)] = x.get(2) + result[x.get(0)];
}
}
}
for(ArrayList<Integer> x : edges){
if(x.get(2) + result[x.get(0)] < result[x.get(1)]){
result[x.get(1)] = 1000000000;
}
}
return result[dest]>100000?1000000000:result[dest];
}
}
class Node{
int from;
int to;
int weight;
Node(int _from,int _to,int _weight){
from = _from;
to = _to;
weight = _weight;
}
}