Floyd算法

Floyd算法

弗洛伊德算法,用来计算多源最短路径(任意两个点之间的最短路径)

符号描述

  • D(i,j)
    • 节点i到节点j的最短距离
  • N(i,j)
    • 节点i到节点j的下一跳节点

思维

  1. 如果某个节点位于起点到终点的最短路径上
    • D(i,j)=D(i,k)+D(k,j)
  2. 如果某个节点不位于起点到终点的最短路径上
    • D(i,j)<D(i,k)+D(k,j)

Java

public class Floyd {
    private int [][]graph;
    private int size;
    private int[][] d;
    private int[][] n;

    public Floyd(int[][] graph) {
        this.graph = graph;
        size=graph.length;
        d=new int[size][size];
        n=new int[size][size];
        for (int i=0;i<size;i++)
            for (int j=0;j<size;j++){
                //拷贝graph
                d[i][j]=graph[i][j];
                    n[i][j]=j;
            }
        cal();
    }
    private void cal() {
        //经过点
        for (int through = 0; through < size; through++){
            //d的遍历
            for (int start = 0; start < size; start++) {
                //通过点和起点重合
                if (start == through)
                    continue;
                for (int end = 0; end < size; end++) {
                    //起点和终点重合或通过点和终点重合
                    if ( start == end || end == through)
                        continue;
                    int distance = d[start][through] + d[through][end];
                    if (distance < d[start][end]) {
                        d[start][end] = distance;
                        n[start][end] = through;
                    }
                }
            }
        }
    }
    public void display(int start,int end){
        String result=""+start;
        while (n[start][end]!=end){
            result+="->"+n[start][end];
            start=n[start][end];
        }
        result+="->"+end;
        System.out.println(result);
    }

    public static void main(String[] args) {
        int INF=Integer.MAX_VALUE/2;
        int[][] graph=new int[][]{
                {INF,-1,3,INF,INF},
                {INF,INF,3,2,2},
                {INF,INF,INF,INF,INF},
                {INF,1,5,INF,INF},
                {INF,INF,INF,INF,-3}
        };
        Floyd floyd=new Floyd(graph);
        floyd.display(0,4);
    }
}

相关推荐