forked from tangorishi/learnJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Floyd Warshall algorithm tangorishi#38
Signed-off-by: PAYAL KUMARI <[email protected]>
- Loading branch information
1 parent
6b7d896
commit b919702
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |