-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path105. BellmanFord.java
More file actions
31 lines (27 loc) · 880 Bytes
/
105. BellmanFord.java
File metadata and controls
31 lines (27 loc) · 880 Bytes
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
// User function Template for Java
class Solution {
static int[] bellmanFord(int V, int[][] edges, int src) {
// Write your code here
int[] dist = new int[V];
Arrays.fill(dist,(int)(1e8));
dist[src] = 0;
for(int i=0;i<V-1;i++){
for(int[] it : edges){
int u = it[0], v = it[1], wt = it[2];
if(dist[u] != 1e8 && dist[u]+wt < dist[v]){
dist[v] = dist[u] + wt;
}
}
}
//nth relaxation to check if thre is -ve cycle
for(int[] it : edges){
int u = it[0], v = it[1], wt = it[2];
if(dist[u] != 1e8 && dist[u]+wt < dist[v]){
int[] temp = new int[1];
temp[0] = -1;
return temp;
}
}
return dist;
}
}