-
Notifications
You must be signed in to change notification settings - Fork 20k
Add FloydWarshall graph algo. #293
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
|
||
public class FloydWarshall { | ||
|
||
private final static int INF = 99999; | ||
|
||
private static void printMatrix(int [][] matrix) { | ||
|
||
int n_vertices = matrix.length; | ||
|
||
for (int i=0; i < n_vertices ; i++) { | ||
for (int j=0; j < n_vertices; j++) { | ||
if (matrix[i][j] == INF) | ||
System.out.print(String.format("%7s", "INF")); | ||
else | ||
System.out.print(String.format("%7d", matrix[i][j])); | ||
} | ||
System.out.println(); | ||
} | ||
} | ||
|
||
private static void findShortestPaths(int[][] graph) { | ||
|
||
int n_vertices = graph.length; | ||
int [][] dp_distances = new int[n_vertices][n_vertices]; | ||
|
||
// Copy graph | ||
for (int i = 0; i < n_vertices; i++) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use curly braces. see |
||
dp_distances[i] = graph[i].clone(); | ||
|
||
for (int k=0; k < n_vertices ; k++) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use curly braces. see |
||
for (int i=0; i < n_vertices; i++) | ||
for (int j=0; j < n_vertices; j++) | ||
dp_distances[i][j] = Math.min(dp_distances[i][j], dp_distances[i][k] + dp_distances[k][j]); | ||
|
||
printMatrix(dp_distances); | ||
} | ||
|
||
public static void main(String args[]) { | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Put in some comments in your code. |
||
int graph[][] = { {0, 5, INF, 10}, | ||
{INF, 0, 3, INF}, | ||
{INF, INF, 0, 1}, | ||
{INF, INF, INF, 0} | ||
}; | ||
|
||
System.out.println("To the given graph, the shortest distances between every pair of vertices are: \n"); | ||
findShortestPaths(graph); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please use curly braces. see