- /*
- *
- * 尋求最短路徑
- *
- */
- public class ShortPath {
- public static void main(String[] args) {
- int[][] am = {{1,2,10},{2,3,20},{2,4,25},{3,5,18}
- ,{4,5,22},{4,6,95},{5,6,77}};//每個邊
- /* Dijkstra d = new Dijkstra(am,7);
- d.MatrixPrint();
- System.out.println("Dijkstra 頂點 1 至 個頂點最小距離 : ");
- d.shortestPath(1);
- System.out.println("Dijkstra 頂點 2 至 個頂點最小距離 : ");
- d.shortestPath(2);
- System.out.println("Dijkstra 頂點 3 至 個頂點最小距離 : ");
- d.shortestPath(3);
- System.out.println("Dijkstra 頂點 4 至 個頂點最小距離 : ");
- d.shortestPath(4);*/
- //"Floyd 方法 : "
- System.out.println("Floyd 方法 : ");
- new Floyd(am,7).PrintList(); ;
- }
- }
- class Floyd extends Adjacency{ //Adjacency 請觀看 Dijkstra文章
- int[][] A ;
- int[][] a ;
- int k = 1;//為次方
- Floyd(int[][] M, int n) {
- super(M, n);
- //Copy 矩陣
- A = Arrays.copyOf(Matrix, Matrix.length);
- }
- int min(int A , int A1){
- return A<A1? A : A1 ; //最小值為最短距離
- }
- int A(int k , int i , int j){ //取出矩陣值
- int value = A[i][j] ;
- return value;
- }
- void Floyd(){
- a = new int[A.length][A.length];
- for(int r = 1 ; r < A.length; r++)
- for(int c = 1 ; c < A.length; c++)
- 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);
- A = a ;//將a的刺件交給A
- if(k == A.length-1) return ;
- k++ ;
- Floyd() ;
- }
- void PrintList(){
- Floyd();
- for(int r = 1 ; r < A.length; r++){
- for(int c = 1 ; c < A.length; c++){
- System.out.print(r+" to "+c+" 最短距離 : ");
- if(A[r][c] == 999)
- System.out.println("∞"+" ");
- else
- System.out.println(A[r][c]+" ");
- }
- System.out.println();
- }
- }
- }
2017年8月5日 星期六
(Java) 尋求最短路徑 -- Floyd 公式運用
訂閱:
張貼留言 (Atom)

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