Skip to content

Commit

Permalink
Create Floyd Warshall algorithm tangorishi#38
Browse files Browse the repository at this point in the history
Signed-off-by: PAYAL KUMARI <[email protected]>
  • Loading branch information
PayalKumari10 authored Oct 30, 2023
1 parent 6b7d896 commit b919702
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Floyd Warshall algorithm #38
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
public class FloydWarshallAlgorithm {
public static void floydWarshall(int[][] graph) {
int V = graph.length;
int[][] dist = new int[V][V];

// Initialize the distance matrix with the graph
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}

// Perform the Floyd-Warshall 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] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE &&
dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

// Print the shortest path distances
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == Integer.MAX_VALUE) {
System.out.print("INF\t");
} else {
System.out.print(dist[i][j] + "\t");
}
}
System.out.println();
}
}

public static void main(String[] args) {
int V = 4; // Number of vertices

int[][] graph = {
{0, 3, Integer.MAX_VALUE, 0},
{Integer.MAX_VALUE, 0, 2, Integer.MAX_VALUE},
{Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1},
{8, Integer.MAX_VALUE, Integer.MAX_VALUE, 0}
};

floydWarshall(graph);
}
}

0 comments on commit b919702

Please sign in to comment.