anuradhawick

Floyd Warshall Algorithm

Dec 23rd, 2015
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. package GraphAlgorithms.FloydWarshall;
  2.  
  3. /**
  4.  * Created by Anuradha Sanjeewa on 24/12/2015.
  5.  */
  6. public class Main {
  7.     public static void main(String[] args) {
  8.         Graph g = new Graph(4);
  9.         g.addEdge(0, 3, 10);
  10.         g.addEdge(0, 1, 5);
  11.         g.addEdge(1, 2, 3);
  12.         g.addEdge(2, 3, 1);
  13.  
  14.         long[][] result = g.runFloyd();
  15.         // printing the result
  16.         for (int i = 0; i < result.length; i++) {
  17.             for (int j = 0; j < result.length; j++) {
  18.                 if (result[i][j] == Integer.MAX_VALUE) {
  19.                     System.out.format("%5s", "INF");
  20.                 } else {
  21.                     System.out.format("%5d", result[i][j]);
  22.                 }
  23.             }
  24.             System.out.println("");
  25.         }
  26.     }
  27. }
  28.  
  29. class Graph {
  30.     long[][] graph;
  31.  
  32.     public Graph(int size) {
  33.         graph = new long[size][size];
  34.         for (int i = 0; i < size; i++) {
  35.             for (int j = 0; j < size; j++) {
  36.                 if (i == j) {
  37.                     graph[i][j] = 0;
  38.                 } else {
  39.                     graph[i][j] = Integer.MAX_VALUE;
  40.                 }
  41.             }
  42.         }
  43.     }
  44.  
  45.     public void addEdge(int u, int v, int d) {
  46.         graph[u][v] = d;
  47.     }
  48.  
  49.     public long[][] runFloyd() {
  50.         long[][] dist = new long[graph.length][graph.length];
  51.         for (int i = 0; i < graph.length; i++) {
  52.             for (int j = 0; j < graph.length; j++) {
  53.                 dist[i][j] = graph[i][j];
  54.             }
  55.         }
  56.  
  57.         // running floyd warhall algorithms
  58.         // consider a pivot node k
  59.         for (int k = 0; k < graph.length; k++) {
  60.             // consider any 2 nodes of the graph
  61.             // starting node
  62.             for (int i = 0; i < graph.length; i++) {
  63.                 // target node
  64.                 for (int j = 0; j < graph.length; j++) {
  65.                     // get the min distance
  66.                     if (dist[i][k] + dist[k][j] < dist[i][j]) {
  67.                         dist[i][j] = dist[i][k] + dist[k][j];
  68.                     }
  69.                 }
  70.             }
  71.         }
  72.  
  73.         return dist;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment