Guest User

Graph FloydWarshall Algorithm

a guest
Nov 19th, 2017
510
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package floyd_warshall;
  2.  
  3. public class TestGraphs {
  4.  
  5.     public static void main(String[] args) {
  6.         Graph g = new Graph(5);
  7.        
  8.         System.out.println("Graph:");
  9.         // add Edges
  10.         g.addEdge(0, 1, 5.2f);
  11.         g.addEdge(0, 2, 10.3f);
  12.         g.addEdge(0, 3, 12.8f);
  13.         g.addEdge(1, 3, 7.4f);
  14.         g.addEdge(1, 4, 16.2f);
  15.         g.addEdge(2, 1, 1.4f);
  16.         g.addEdge(2, 3, 2.3f);
  17.         g.addEdge(3, 4, 8.5f);
  18.         g.addEdge(4, 2, 2.7f);
  19.         g.addEdge(4, 1, 13.7f);
  20.  
  21.         // print Graph
  22.         g.printGraph();
  23.  
  24.         // Floyd-Warshall All Pair Shortest Path Algorithm
  25.         System.out.println("Floyd-Warshall All Pair Shortest Path Matrix:");
  26.         FloydWarshall(g);
  27.     }
  28.  
  29.     public static void FloydWarshall(Graph g) {
  30.         int V = g.getvCount();
  31.        
  32.         // to store the calculated distances
  33.         float dist[][] = new float[V][V];
  34.  
  35.         // initialize with adjacency matrix weight values
  36.         for (int i = 0; i < V; i++) {
  37.             for (int j = 0; j < V; j++) {
  38.                 dist[i][j] = g.getAdj()[i][j];
  39.             }
  40.         }
  41.  
  42.         // loop through all vertices one by one
  43.         for (int k = 0; k < V; k++) {
  44.             // pick all as source
  45.             for (int i = 0; i < V; i++) {
  46.                 // pick all as destination
  47.                 for (int j = 0; j < V; j++) {
  48.                     // If k is on the shortest path from i to j
  49.                     if (dist[i][k] + dist[k][j] < dist[i][j]) {
  50.                         // update the value of dist[i][j]
  51.                         dist[i][j] = dist[i][k] + dist[k][j];
  52.                     }
  53.                 }
  54.             }
  55.         }
  56.        
  57.         // shortest path matrix
  58.         for (int i = 0; i < V; i++) {
  59.             for (int j = 0; j < V; j++) {
  60.                 // if value is infinity
  61.                 if (dist[i][j] == Float.MAX_VALUE)
  62.                     System.out.print("INF ");
  63.                 else
  64.                     System.out.print(dist[i][j] + "   ");
  65.             }
  66.             System.out.println();
  67.         }
  68.        
  69.     }
  70.  
  71. }
Add Comment
Please, Sign In to add comment