Guest User

Untitled

a guest
May 24th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import static java.lang.String.format;
  2. import java.util.Arrays;
  3.  
  4.  
  5.  
  6. public class FloydWarshall {
  7.  
  8.  
  9. public static void main(String[] args) {
  10. int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}};
  11. int numVertices = 4;
  12.  
  13. floydWarshall(weights, numVertices);
  14. }
  15.  
  16. static void floydWarshall(int[][] weights, int numVertices) {
  17.  
  18. double[][] dist = new double[numVertices][numVertices];
  19. for (double[] row : dist)
  20. Arrays.fill(row, Double.POSITIVE_INFINITY);
  21.  
  22. for (int[] w : weights)
  23. dist[w[0] - 1][w[1] - 1] = w[2];
  24.  
  25. int[][] next = new int[numVertices][numVertices];
  26. for (int i = 0; i < next.length; i++) {
  27. for (int j = 0; j < next.length; j++)
  28. if (i != j)
  29. next[i][j] = j + 1;
  30. }
  31.  
  32. for (int k = 0; k < numVertices; k++)
  33. for (int i = 0; i < numVertices; i++)
  34. for (int j = 0; j < numVertices; j++)
  35. if (dist[i][k] + dist[k][j] < dist[i][j]) {
  36. dist[i][j] = dist[i][k] + dist[k][j];
  37. next[i][j] = next[i][k];
  38. }
  39.  
  40. printResult(dist, next);
  41. }
  42.  
  43. static void printResult(double[][] dist, int[][] next) {
  44. System.out.println("pair dist path");
  45. for (int i = 0; i < next.length; i++) {
  46. for (int j = 0; j < next.length; j++) {
  47. if (i != j) {
  48. int u = i + 1;
  49. int v = j + 1;
  50. String path = format("%d -> %d %2d %s", u, v,
  51. (int) dist[i][j], u);
  52. do {
  53. u = next[u - 1][v - 1];
  54. path += " -> " + u;
  55. } while (u != v);
  56. System.out.println(path);
  57. }
  58. }
  59. }
  60. }
  61. }
Add Comment
Please, Sign In to add comment