-
Notifications
You must be signed in to change notification settings - Fork 1
/
BellmanFord.java
144 lines (124 loc) · 6.08 KB
/
BellmanFord.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package org.hit.internetprogramming.eoh.server.graph.algorithm;
import lombok.NonNull;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.tuple.Pair;
import org.hit.internetprogramming.eoh.common.graph.IGraph;
import org.hit.internetprogramming.eoh.server.action.ActionThreadService;
import org.hit.internetprogramming.eoh.server.common.exception.NegativeWeightCycleException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
/**
* A class that implements Bellman-Ford algorithm in order to find shortest paths in a weighted graph.
*
* @param <V> Type of elements in an {@link IGraph} (We use the {@link org.hit.internetprogramming.eoh.common.mat.Index} class)
* @author Haim Adrian
* @since 18-Jul-21
*/
@Log4j2
public class BellmanFord<V> implements ShortestPathAlgorithm<V> {
/**
* Algorithm: BELLMAN-FORD(G, w, s)<br/>
* <pre>{@code
* for each v ∈ G.V do:
* v.distance = ∞
* s.distance = 0
* repeat |G.V|-1 times:
* for each edge (u, v) ∈ G.E do:
* RELAX(u, v, w) // Update weight if smaller
* for each edge (u, v) ∈ G.E do:
* if v.distance > u.distance + w(u, v) then:
* return FALSE // (Error - a negative cycle found)
* return TRUE
* }</pre>
* @param graph The graph to traverse, starting from its root.
* @return All visited vertices, and their details (distance and path)
*/
@Override
public Map<V, VertexDistanceInfo<V>> traverse(@NonNull IGraph<V> graph) {
log.info("BellmanFord traverse start");
// Use a thread safe structure
Map<V, VertexDistanceInfo<V>> visitedVertices = new ConcurrentHashMap<>();
List<V> vertices = graph.getVertices();
List<Pair<V, V>> edges = graph.getEdges();
// Step 1: Source vertex to source vertex weight 0, which means no move.
visitedVertices.computeIfAbsent(graph.getRoot(), VertexDistanceInfo::new).setDistance(0);
//List<Callable<Void>> tasks = new ArrayList<>();
// Step 2: Relax edges repeatedly
// Repeat |V|-1 times: (Longest simple path can be up to |V|-1 edges)
for (int i = 1; i < vertices.size(); i++) {
new RelaxTask<>(graph, edges, visitedVertices).call();
}
// It does not work, running it in parallel... Use Dijkstra instead.
/*try {
ActionThreadService.getInstance().invokeAll(tasks);
} catch (InterruptedException e) {
log.error("Bellman-Ford parallel search was interrupted.", e);
}*/
// Step 3: Check for negative weight cycles
// For each edge (u, v) in edges do:
for (Pair<V, V> edge : edges) {
// Weight of the edge between u to v
int weight = graph.getValue(edge.getRight());
if (visitedVertices.get(edge.getLeft()).getDistance() + weight < visitedVertices.get(edge.getRight()).getDistance()) {
throw new NegativeWeightCycleException("Graph contains negative cycle. No shortest path can be found. [Edge=" + edgeToString(visitedVertices, edge) + ", weight=" + weight + "]");
}
}
log.info("BellmanFord traverse end");
return visitedVertices;
}
/**
* See {@link #traverse(IGraph)}
* @param graph The graph to traverse, starting from its root.
* @param destination Where to stop. This is irrelevant for Bellman-Ford
* @return All visited vertices, and their details (distance and path)
*/
@Override
public Map<V, VertexDistanceInfo<V>> traverse(@NonNull IGraph<V> graph, @SuppressWarnings("unused") V destination) {
return traverse(graph);
}
private String edgeToString(Map<V, VertexDistanceInfo<V>> visitedVertices, Pair<V, V> edge) {
V u = edge.getLeft();
V v = edge.getRight();
return String.format("(%s, w=%s) -> (%s, w=%s)", u, visitedVertices.get(u).getDistance(), v, visitedVertices.get(v).getDistance());
}
private static class RelaxTask<V> implements Callable<Void> {
private final IGraph<V> graph;
private final List<Pair<V, V>> edges;
private final Map<V, VertexDistanceInfo<V>> visitedVertices;
public RelaxTask(IGraph<V> graph, List<Pair<V, V>> edges, Map<V, VertexDistanceInfo<V>> visitedVertices) {
this.graph = graph;
this.edges = edges;
this.visitedVertices = visitedVertices;
}
@Override
public Void call() {
// For each edge (u, v) in edges do:
for (Pair<V, V> edge : edges) {
// If thread service instructed to shutdown now, we cannot continue executing.
if (ActionThreadService.getInstance().isShutdownNow()) {
break;
}
// Weight of the edge between u to v
int weight = graph.getValue(edge.getRight());
long uVertexWeight = visitedVertices.computeIfAbsent(edge.getLeft(), VertexDistanceInfo::new).getDistance();
long vVertexWeight = visitedVertices.computeIfAbsent(edge.getRight(), VertexDistanceInfo::new).getDistance();
// Avoid of overflow
if (uVertexWeight != Long.MAX_VALUE) {
long newWeight = uVertexWeight + weight;
if (newWeight < vVertexWeight) {
// Clear old parents
visitedVertices.get(edge.getRight()).getParents().clear();
visitedVertices.get(edge.getRight()).getParents().add(edge.getLeft());
// Update distance
visitedVertices.get(edge.getRight()).setDistance(newWeight);
} else if (newWeight == vVertexWeight) {
visitedVertices.get(edge.getRight()).getParents().add(edge.getLeft());
}
}
}
return null;
}
}
}