Skip to content

Commit b20bd00

Browse files
committed
Add Floyd-Warshall implementation
1 parent 5084307 commit b20bd00

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.packt.datastructuresandalg.lesson6.floydwarshall;
2+
3+
public class FloydWarshall {
4+
int[][] adj;
5+
6+
public FloydWarshall(int nodes) {
7+
this.adj = new int[nodes][nodes];
8+
for (int i = 0; i < adj.length; i++) {
9+
for (int j = 0; j < adj[i].length; j++) {
10+
if (i == j)
11+
this.adj[i][j] = 0;
12+
else
13+
this.adj[i][j] = Integer.MAX_VALUE;
14+
}
15+
}
16+
}
17+
18+
public void addEdge(int u, int v, int weight) {
19+
adj[u][v] = Math.min(adj[u][v], weight);
20+
}
21+
22+
@Override
23+
public String toString() {
24+
String res = "";
25+
for (int i = 0; i < this.adj.length; i++) {
26+
res += (i + ":");
27+
for (int j = 0; j < this.adj[i].length; j++)
28+
res += (" " + adj[i][j]);
29+
if (i + 1 < adj.length)
30+
res += "\n";
31+
}
32+
return res;
33+
}
34+
35+
public void run() {
36+
for (int k = 0; k < adj.length; k++) {
37+
for (int i = 0; i < adj.length; i++) {
38+
if (adj[i][k] >= Integer.MAX_VALUE)
39+
continue;
40+
for (int j = 0; j < adj.length; j++) {
41+
if (adj[k][j] >= Integer.MAX_VALUE)
42+
continue;
43+
adj[i][j] = Math.min(adj[i][j], adj[i][k] + adj[k][j]);
44+
}
45+
}
46+
}
47+
}
48+
49+
public static void main(String [] args) {
50+
FloydWarshall g = new FloydWarshall(5);
51+
g.addEdge(0, 1, 10);
52+
g.addEdge(0, 3, 5);
53+
g.addEdge(1, 3, 2);
54+
g.addEdge(1, 2, 1);
55+
g.addEdge(2, 4, 4);
56+
g.addEdge(3, 1, 3);
57+
g.addEdge(3, 2, 9);
58+
g.addEdge(3, 4, 2);
59+
g.addEdge(4, 2, 6);
60+
g.run();
61+
System.out.println(g);
62+
}
63+
64+
}

0 commit comments

Comments
 (0)