-
Notifications
You must be signed in to change notification settings - Fork 115
/
FloydWarshallTest.java
64 lines (55 loc) Β· 1.59 KB
/
FloydWarshallTest.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
public class FloydWarshallTest {
public static void main(String[] args) {
FloydWarshall fw = new FloydWarshall(5);
fw.setWeight(1, 3, 5);
fw.setWeight(1, 2, 7);
fw.setWeight(1, 4, -3);
fw.setWeight(3, 4, 3);
fw.setWeight(3, 5, 3);
fw.setWeight(4, 2, 3);
fw.setWeight(4, 5, 6);
fw.setWeight(5, 3, 2);
fw.getShortestDistance();
}
}
class FloydWarshall {
private int N;
private int[][] D;
private final static int INF = Integer.MAX_VALUE;
public FloydWarshall(int N) {
this.N = N;
D = new int[N+1][N+1];
initDistance();
}
private void initDistance() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (i != j) D[i][j] = INF;
}
}
}
public void setWeight(int i, int j, int w) {
D[i][j] = w;
}
public void getShortestDistance() {
/* Floyd-Warshall */
for (int k = 1; k <= N; k++){
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (D[i][k] == INF || D[k][j] == INF) continue;
D[i][j] = Math.min(D[i][j], D[i][k] + D[k][j]);
}
}
}
printDistance();
}
private void printDistance() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (D[i][j] == INF) System.out.print("β ");
else System.out.print(D[i][j] + " ");
}
System.out.println();
}
}
}