-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path*BellmanFord.java
More file actions
46 lines (40 loc) · 950 Bytes
/
*BellmanFord.java
File metadata and controls
46 lines (40 loc) · 950 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class BellmanFord {
static final long max = Long.MAX_VALUE / 2;
static int n, m;
static ArrayDeque<edge>[] edges;
static long[] bellmanFord(int start) {
long[] dist = new long[n];
Arrays.fill(dist, max);
dist[start] = 0;
for(int k = 0; k < n - 1; ++k) {
for(int u = 0; u < n; ++u) {
for(edge e : edges[u]) {
if(dist[u] != max && dist[u] + e.w < dist[e.v]) {
dist[e.v] = dist[u] + e.w;
}
}
}
}
// check for negative cycles
for(int u = 0; u < n; ++u) {
for(edge e : edges[u]) {
if(dist[u] != max && dist[u] + e.w < dist[e.v]) {
// do BFS
ArrayDeque<Integer> ad = new ArrayDeque<>();
dist[u] = -max;
ad.add(u);
while(!ad.isEmpty()) {
int curr = ad.poll();
for(edge currE : edges[curr]) {
if(dist[currE.v] != -max) {
dist[currE.v] = -max;
ad.add(currE.v);
}
}
}
}
}
}
return dist;
}
}