Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions FloydWarshall.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// FloydWarshall.java
import java.util.Arrays;

public class FloydWarshall {

static final int INF = 99999;

public static void floydWarshall(int[][] graph) {
int V = graph.length;
int[][] dist = new int[V][V];

// Initialize distance array
for (int i = 0; i < V; i++) {
dist[i] = Arrays.copyOf(graph[i], V);
}

// Core algorithm
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

printSolution(dist);
}

static void printSolution(int[][] dist) {
System.out.println("Shortest distance between every pair:");
for (int i = 0; i < dist.length; i++) {
for (int j = 0; j < dist.length; j++) {
if (dist[i][j] == INF) System.out.print("INF ");
else System.out.print(dist[i][j] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {
int[][] graph = {
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0}
};

floydWarshall(graph);
}
}
Loading