Skip to content

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

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Data Structures/Graphs/FloydWarshall.java
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)

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

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++)

Choose a reason for hiding this comment

The 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++)

Choose a reason for hiding this comment

The 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[]) {

Choose a reason for hiding this comment

The 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);
}
}