编程语言
首页 > 编程语言> > 44-Floyd 算法

44-Floyd 算法

作者:互联网

1. 概述

2. 算法思想

3. 算法分析

4. 代码实现

public class FloydAlgorithm {
    public static void main(String[] args) {
        char[] vertexs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
        int[][] matrix = new int[vertexs.length][vertexs.length];
        final int N = 65535; // 表示不可以连接
        matrix[0] = new int[] { 0, 5, 7, N, N, N, 2 };
        matrix[1] = new int[] { 5, 0, N, 9, N, N, 3 };
        matrix[2] = new int[] { 7, N, 0, N, 8, N, N };
        matrix[3] = new int[] { N, 9, N, 0, N, 4, N };
        matrix[4] = new int[] { N, N, 8, N, 0, 5, 4 };
        matrix[5] = new int[] { N, N, N, 4, 5, 0, 6 };
        matrix[6] = new int[] { 2, 3, N, N, 4, 6, 0 };
        Graph graph = new Graph(vertexs, matrix);
        graph.show();
        graph.floyd();
        System.out.println();
        graph.show();
    }
}

class Graph {
    int vCount;
    char[] vertexs;
    int[][] dis; // 保存距离
    int[][] pre; // 保存前驱
    
    public Graph(char[] vertexs, int[][] dis) {
        super();
        vCount = vertexs.length;
        this.vertexs = vertexs;
        this.dis = dis;
        this.pre = new int[vCount][vCount];
        for(int i = 0; i < vCount; i++)
            for(int j = 0; j < vCount; j++)
                pre[i][j] = i;
    }
    
    public void floyd() {
        int len;
        for(int k = 0; k < vCount; k++) // k: 中间顶点
            for(int i = 0; i < vCount; i++) // i: 出发顶点
                for(int j = 0; j < vCount; j++) { // j: 终点
                    len = dis[i][k] + dis[k][j];
                    if(dis[i][j] > len) {
                        dis[i][j] = len;
                        pre[i][j] = k;
                    }
                }
    }
    
    public void show() {
        System.out.print("  ");
        for(int i = 0; i < vCount; i++)
            System.out.printf("%8c  ", vertexs[i]);
        System.out.println();
        for(int i = 0; i < vCount; i++) {
            System.out.print(vertexs[i]+"  ");
            for(int j = 0; j < vCount; j++)
                System.out.printf("%c(%5d)  ", vertexs[pre[i][j]], dis[i][j]);
            System.out.println();
        }
    }
}

标签:vCount,arcs,int,44,路径,算法,Floyd,顶点,vertexs
来源: https://www.cnblogs.com/liujiaqi1101/p/12489977.html