Java实现"最短路径FLOYD算法”

/**

 * title_最短路径问题 made by 任辉 2010-10-22

 */

 

public class Task7_15 {

    private int[][] l = { { 0, 0, 0, 0, 0 }, { 0, 0, 7, 1, 6 },

                          { 0, 100, 0, 9, 100 },

                          { 0, 4, 4, 0, 2 },

                          { 0, 1, 100, 100, 0 } };//存储各个边的长度i~j的二维数组

    private int[][] D;//存储最终结果的二维数组

 

    /** 构造 */

    public Task7_15() {

       System.out.println("L:中保存所要求的各个边(i,j)间的长度");

       printL(l);

       FLOYD();

       System.out.println("D:中保存所要求的各个顶点(i,j)间的最短路径");

       printL(D);

    }

    /** 算法FLOYD */

    public void FLOYD() {

       D = l;

       for (int k = 1; k < l.length; k++)

           for (int i = 1; i < l.length; i++)

              for (int j = 1; j < l.length; j++)

                  D[i][j] = min(D[i][j], D[i][k] + D[k][j]);

    }

 

    /**二者求最小*/

    public int min(int a, int b) {

       if (a >= b)

           return b;

       else

           return a;

    }

 

    /**打印表*/

    public void printL(int [][]a) {

       for (int i = 0; i < 5; i++) {

           for (int j = 0; j < 5; j++) {

              System.out.printf("%4d", l[i][j]);

           }

           System.out.println("");

       }

    }

 

    /** mainBase */

    public static void main(String[] args) {

       new Task7_15();

    }

}

你可能感兴趣的:(Java实现"最短路径FLOYD算法”)