1203-2019-算法-弗洛伊德算法(最短路径算法-Floyd算法)

Floyd算法与Dijkstra不一样的地方在于他可以计算出任意一个顶点到其他顶点的最短距离。最后全部保存在dis[ ][ ] 的二维数组中。

package Floyd;

import java.util.Arrays;

/**
 * @author pdzz
 * @create 2019-12-03 10:03
 */
public class Floyd {
    public static void main(String[] args) {
        char[] vertex = {'A','B','C','D','E','F','G'};
        int[][] matrix = new int[vertex.length][vertex.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(vertex.length, matrix, vertex);
        graph.floyd();
        graph.show();
    }

}
class Graph{
    private char[] vertex;
    private int[][] dis;
    private int[][] pre;//到达保存目标顶点的前驱顶点

    public Graph(int len,int[][] matrix,char[] vertex){
        this.vertex = vertex;
        this.dis = matrix;
        this.pre = new int[len][len];
        for (int i = 0; i < len; i++) {
            Arrays.fill(pre[i],i);
        }

    }
    public void show(){
        for (int i = 0; i < dis.length; i++) {
            for (int j = 0; j < dis.length; j++) {
                System.out.print(dis[i][j] + " ");
            }
            System.out.println();
        }
    }

    public void floyd(){
        int len;
        for (int k = 0; k < vertex.length; k++) {
            //把k看成中间顶点
            for (int i = 0; i < vertex.length; i++) {
                //把i看成起点
                for (int j = 0; j < vertex.length; j++) {
                    //把j看成目的顶点
                    len = dis[i][k] + dis[k][j];
                    if (len < dis[i][j]){
                        dis[i][j] = len;
                        pre[i][j] = pre[k][j];
                    }
                }
            }
        }
    }
}

From 尚硅谷韩顺平老师的Java数据结构的视频

你可能感兴趣的:(算法)