Floyd(多源最短路徑)

java實現Floyd算法

源代碼
圖的結構java實現

Floyd

public class Floyd {
    private static int INF = Integer.MAX_VALUE;

    public static void floyd(GraphMatrix graph) {
        int vertexNum = graph.getVertexNum();
        int[][] distance = new int[vertexNum][vertexNum];

        // 初始化距離矩陣
        for (int i = 0; i < vertexNum; i++) {
            for (int j = 0; j < vertexNum; j++) {
                distance[i][j] = graph.edges[i][j];
                if (i != j && distance[i][j] == 0) {
                    distance[i][j] = INF;
                }
            }
        }
        System.out.println("距離矩陣:");
        showDistance(distance, vertexNum);

        //循環更新矩陣的值
        for (int k = 0; k < vertexNum; k++) {
            for (int i = 0; i < vertexNum; i++) {
                for (int j = 0; j < vertexNum; j++) {
                    //以k爲中間點,如果i->k->j的總距離小於當前i->j的距離,更新距離矩陣
                    int temp = (distance[i][k] == INF || distance[k][j] == INF) ?
                            INF : distance[i][k] + distance[k][j];
                    if (distance[i][j] > temp) {
                        distance[i][j] = temp;
                    }
                }
            }
            System.out.println("count" + k);
            showDistance(distance, vertexNum);
        }

        // 打印floyd最短路徑的結果
        System.out.println("Floyd最短路徑的結果:");
        showDistance(distance, vertexNum);
    }

    private static void showDistance(int[][] distance, int vertexNum) {
        for (int i = 0; i < vertexNum; i++) {
            for (int j = 0; j < vertexNum; j++) {
                if (distance[i][j] == INF) {
                    System.out.printf("%4s ", "INF");
                } else {
                    System.out.printf("%4d ", distance[i][j]);
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        GraphMatrix<String> graph = new GraphMatrix<>("ABCD");
        graph.type = GraphMatrix.GraphType.DIRECTED_GRAPH;
        graph.addEdge("A", "B", 1);
        graph.addEdge("A", "C", 2);
        graph.addEdge("A", "D", 3);
        graph.addEdge("B", "A", 4);
        graph.addEdge("C", "B", 5);
        graph.addEdge("C", "D", 1);
        graph.addEdge("D", "B", 1);
        graph.addEdge("D", "C", 2);
        graph.information();
        floyd(graph);
    }
}

log

距離矩陣:
   0    1    2    3 
   4    0  INF  INF 
 INF    5    0    1 
 INF    1    2    0 
count0
   0    1    2    3 
   4    0    6    7 
 INF    5    0    1 
 INF    1    2    0 
count1
   0    1    2    3 
   4    0    6    7 
   9    5    0    1 
   5    1    2    0 
count2
   0    1    2    3 
   4    0    6    7 
   9    5    0    1 
   5    1    2    0 
count3
   0    1    2    3 
   4    0    6    7 
   6    2    0    1 
   5    1    2    0 
Floyd最短路徑的結果:
   0    1    2    3 
   4    0    6    7 
   6    2    0    1 
   5    1    2    0 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章