Skip to content

Commit

Permalink
Merge pull request #326 from Hardvan/floyd-warshall-java
Browse files Browse the repository at this point in the history
Add Floyd Warshall algorithm in Java
  • Loading branch information
kelvins authored Oct 31, 2023
2 parents 3a3b293 + 6e441bc commit c8517d5
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- Java -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/java/FloydWarshall.java">
<img align="center" height="25" src="./logos/java.svg" />
</a>
</td>
<td> <!-- Python -->
Expand Down
66 changes: 66 additions & 0 deletions src/java/FloydWarshall.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Floyd-Warshall algorithm in Java
* All pairs shortest path algorithm
* Time Complexity: O(n³)
* Space Complexity: O(n²)
*/

public class FloydWarshall {

public static void showMatrix(long[][] matriz, int nroVertices) {
for (int i = 0; i < nroVertices; i++) {
for (int j = 0; j < nroVertices; j++) {
if (matriz[i][j] < 10) {
System.out.print(" " + matriz[i][j] + " ");
} else {
System.out.print(matriz[i][j] + " ");
}
}

System.out.println();
}
System.out.println();
}

public static void main(String[] args) {
int nroVertices = 5;
long[][] matriz = {
{0, 2, 10, 5, 7},
{2, 0, 3, 3, 1},
{10, 3, 0, 1, 2},
{5, 3, 1, 0, Long.MAX_VALUE},
{7, 1, 2, 2, 0}
};

// Display the original matrix
System.out.println("Original matrix:");
showMatrix(matriz, nroVertices);

floydWarshall(matriz, nroVertices);

// Display the updated matrix
System.out.println("Updated matrix:");
showMatrix(matriz, nroVertices);

// Show all shortest paths
System.out.println();
for (int i = 0; i < nroVertices; i++) {
for (int x = 0; x < nroVertices; x++) {
System.out.println("Shortest distance from " + i + " to " + x + " = " + matriz[x][i] + ".");
}
}
System.out.println();
}

public static void floydWarshall(long[][] matriz, int n) {
for (int x = 0; x < n; x++) { // Intermediary vertex
for (int y = 0; y < n; y++) { // Origin vertex
for (int z = 0; z < n; z++) { // Destination vertex
if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) {
matriz[y][z] = matriz[y][x] + matriz[x][z];
}
}
}
}
}
}

0 comments on commit c8517d5

Please sign in to comment.