Skip to content

Commit b4e14ba

Browse files
committed
Add Floyd-Warshall algorithm in Java with example usage
1 parent f8688ba commit b4e14ba

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

FloydWarshall.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// FloydWarshall.java
2+
import java.util.Arrays;
3+
4+
public class FloydWarshall {
5+
6+
static final int INF = 99999;
7+
8+
public static void floydWarshall(int[][] graph) {
9+
int V = graph.length;
10+
int[][] dist = new int[V][V];
11+
12+
// Initialize distance array
13+
for (int i = 0; i < V; i++) {
14+
dist[i] = Arrays.copyOf(graph[i], V);
15+
}
16+
17+
// Core algorithm
18+
for (int k = 0; k < V; k++) {
19+
for (int i = 0; i < V; i++) {
20+
for (int j = 0; j < V; j++) {
21+
if (dist[i][k] + dist[k][j] < dist[i][j]) {
22+
dist[i][j] = dist[i][k] + dist[k][j];
23+
}
24+
}
25+
}
26+
}
27+
28+
printSolution(dist);
29+
}
30+
31+
static void printSolution(int[][] dist) {
32+
System.out.println("Shortest distance between every pair:");
33+
for (int i = 0; i < dist.length; i++) {
34+
for (int j = 0; j < dist.length; j++) {
35+
if (dist[i][j] == INF) System.out.print("INF ");
36+
else System.out.print(dist[i][j] + " ");
37+
}
38+
System.out.println();
39+
}
40+
}
41+
42+
public static void main(String[] args) {
43+
int[][] graph = {
44+
{0, 3, INF, 7},
45+
{8, 0, 2, INF},
46+
{5, INF, 0, 1},
47+
{2, INF, INF, 0}
48+
};
49+
50+
floydWarshall(graph);
51+
}
52+
}

0 commit comments

Comments
 (0)