Skip to content

Commit c8517d5

Browse files
authored
Merge pull request kelvins#326 from Hardvan/floyd-warshall-java
Add Floyd Warshall algorithm in Java
2 parents 3a3b293 + 6e441bc commit c8517d5

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ In order to achieve greater coverage and encourage more people to contribute to
135135
</a>
136136
</td>
137137
<td> <!-- Java -->
138-
<a href="./CONTRIBUTING.md">
139-
<img align="center" height="25" src="./logos/github.svg" />
138+
<a href="./src/java/FloydWarshall.java">
139+
<img align="center" height="25" src="./logos/java.svg" />
140140
</a>
141141
</td>
142142
<td> <!-- Python -->

src/java/FloydWarshall.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Floyd-Warshall algorithm in Java
3+
* All pairs shortest path algorithm
4+
* Time Complexity: O(n³)
5+
* Space Complexity: O(n²)
6+
*/
7+
8+
public class FloydWarshall {
9+
10+
public static void showMatrix(long[][] matriz, int nroVertices) {
11+
for (int i = 0; i < nroVertices; i++) {
12+
for (int j = 0; j < nroVertices; j++) {
13+
if (matriz[i][j] < 10) {
14+
System.out.print(" " + matriz[i][j] + " ");
15+
} else {
16+
System.out.print(matriz[i][j] + " ");
17+
}
18+
}
19+
20+
System.out.println();
21+
}
22+
System.out.println();
23+
}
24+
25+
public static void main(String[] args) {
26+
int nroVertices = 5;
27+
long[][] matriz = {
28+
{0, 2, 10, 5, 7},
29+
{2, 0, 3, 3, 1},
30+
{10, 3, 0, 1, 2},
31+
{5, 3, 1, 0, Long.MAX_VALUE},
32+
{7, 1, 2, 2, 0}
33+
};
34+
35+
// Display the original matrix
36+
System.out.println("Original matrix:");
37+
showMatrix(matriz, nroVertices);
38+
39+
floydWarshall(matriz, nroVertices);
40+
41+
// Display the updated matrix
42+
System.out.println("Updated matrix:");
43+
showMatrix(matriz, nroVertices);
44+
45+
// Show all shortest paths
46+
System.out.println();
47+
for (int i = 0; i < nroVertices; i++) {
48+
for (int x = 0; x < nroVertices; x++) {
49+
System.out.println("Shortest distance from " + i + " to " + x + " = " + matriz[x][i] + ".");
50+
}
51+
}
52+
System.out.println();
53+
}
54+
55+
public static void floydWarshall(long[][] matriz, int n) {
56+
for (int x = 0; x < n; x++) { // Intermediary vertex
57+
for (int y = 0; y < n; y++) { // Origin vertex
58+
for (int z = 0; z < n; z++) { // Destination vertex
59+
if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) {
60+
matriz[y][z] = matriz[y][x] + matriz[x][z];
61+
}
62+
}
63+
}
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)