-
Notifications
You must be signed in to change notification settings - Fork 115
/
BellmanFordTest.java
93 lines (78 loc) Β· 2.29 KB
/
BellmanFordTest.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
import java.util.ArrayList;
public class BellmanFordTest {
public static void main(String[] args) {
BellmanFord bf = new BellmanFord(5);
bf.addEdge(3, 5, 3);
bf.addEdge(3, 4, 3);
bf.addEdge(4, 2, 3);
bf.addEdge(5, 3, 2);
bf.addEdge(4, 5, -6);
bf.addEdge(1, 4, 3);
bf.addEdge(1, 3, 5);
bf.addEdge(1, 2, 7);
// bf.printEdges();
bf.getShortestDistance(1);
}
}
class BellmanFord {
private int N;
private ArrayList<Edge> edges;
private final static int INF = Integer.MAX_VALUE;
private int[] D;
public BellmanFord(int N) {
this.N = N;
edges = new ArrayList<>();
D = new int[N+1];
}
public void addEdge(int from, int to, int weight) {
edges.add(new Edge(from, to, weight));
}
public void printEdges() {
for (Edge edge : edges) System.out.println(edge);
}
public void getShortestDistance(int S) {
/* init */
for (int i = 1; i <= N; i++) {
if (i != S) D[i] = INF;
}
/* Bellman-Ford */
boolean negCycle = false;
for (int i = 1; i <= N; i++) {
for (Edge edge : edges) {
int from = edge.from;
int to = edge.to;
int weight = edge.weight;
if (D[from] != INF && D[to] > D[from] + weight) {
if (i == N) {
negCycle = true;
break;
}
D[to] = D[from] + weight;
}
}
}
if (negCycle) System.out.println("μμ μ¬μ΄ν΄μ΄ μ‘΄μ¬ν©λλ€.");
else printDistance();
}
private void printDistance() {
for (int i = 1; i <= N; i++) {
if (D[i] == INF) System.out.print("β ");
else System.out.print(D[i] + " ");
}
System.out.println();
}
static class Edge {
private int from;
private int to;
private int weight;
private Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
@Override
public String toString() {
return from + " --(" + weight + ")--> " + to;
}
}
}