2017年8月5日 星期六

(Java) 尋求最短路徑 -- Floyd 公式運用


  1. /* 
  2.  *  
  3.  * 尋求最短路徑 
  4.  *  
  5.  */  
  6. public class ShortPath {  
  7.   
  8.     public static void main(String[] args) {  
  9.           
  10.          int[][] am = {{1,2,10},{2,3,20},{2,4,25},{3,5,18}  
  11.                                ,{4,5,22},{4,6,95},{5,6,77}};//每個邊  
  12.         /* Dijkstra d = new Dijkstra(am,7);  
  13.          d.MatrixPrint(); 
  14.          System.out.println("Dijkstra 頂點 1 至 個頂點最小距離 : "); 
  15.          d.shortestPath(1); 
  16.          System.out.println("Dijkstra 頂點 2 至 個頂點最小距離 : "); 
  17.          d.shortestPath(2); 
  18.          System.out.println("Dijkstra 頂點 3 至 個頂點最小距離 : "); 
  19.          d.shortestPath(3); 
  20.          System.out.println("Dijkstra 頂點 4 至 個頂點最小距離 : "); 
  21.          d.shortestPath(4);*/  
  22.          //"Floyd 方法 : "  
  23.          System.out.println("Floyd 方法 : ");  
  24.          new Floyd(am,7).PrintList(); ;  
  25.     }  
  26.   
  27. }  
  28. class Floyd extends Adjacency{  //Adjacency 請觀看 Dijkstra文章
  29. int[][] A ;  
  30. int[][] a ;  
  31. int k  = 1;//為次方  
  32.     Floyd(int[][] M, int n) {  
  33.         super(M, n);  
  34.         //Copy 矩陣  
  35.         A = Arrays.copyOf(Matrix, Matrix.length);  
  36.     }  
  37.     int min(int A , int A1){  
  38.         return A<A1? A : A1 ; //最小值為最短距離  
  39.     }  
  40.     int A(int k , int i , int j){  //取出矩陣值  
  41.         int value  = A[i][j] ;  
  42.         return value;  
  43.     }  
  44.     void Floyd(){  
  45.         a = new int[A.length][A.length];          
  46.         for(int r = 1 ; r < A.length; r++)  
  47.             for(int c = 1 ; c < A.length; c++)  
  48.                 a[r][c] =  min(A(k-1, r , c), A(k-1, r , k) + A(k-1, k , c)) ;//  A^k[i][j] = min(A^k-1[i][j] , A^k-1[j][k]+A^k-1[k][j);  
  49.         A = a ;//將a的刺件交給A      
  50.         if(k == A.length-1return ;  
  51.         k++ ;    
  52.         Floyd() ;  
  53.     }  
  54.     void PrintList(){  
  55.         Floyd();  
  56.         for(int r = 1 ; r < A.length; r++){  
  57.             for(int c = 1 ; c < A.length; c++){  
  58.                 System.out.print(r+" to "+c+" 最短距離 : ");  
  59.                 if(A[r][c] == 999)  
  60.                     System.out.println("∞"+"  ");  
  61.                 else  
  62.                     System.out.println(A[r][c]+"  ");  
  63.             }  
  64.             System.out.println();  
  65.         }  
  66.     }  
  67.       
  68. }  

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。