任意两点间的最短路问题(Floyd-Warshall算法)

/*
任意两点间的最短路问题(Floyd-Warshall算法)

*/

import java.util.Scanner;

public class Main {
    //图的顶点数,总边数
    static int V, E;
    //存储所有的边,大小为顶点数
    static int[][] Edges;
    static int[][] d;
    static final int MAX_VALUE = 999999;

    public static void main(String[] args) {
        creatGraph();
        shortPath();
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                System.out.print(d[i][j] + " ");
            }
            System.out.println();
        }
    }

    static void shortPath() {
        d = new int[V][V];
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                d[i][j] = Edges[i][j];
            }
        }
        for (int k = 0; k < V; k++)
            for (int i = 0; i < V; i++) {
                for (int j = 0; j < V; j++) {
                    d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
                }
            }
    }

    static void creatGraph() {
        Scanner sc = new Scanner(System.in);
        V = sc.nextInt();
        E = sc.nextInt();
        Edges = new int[V][V];
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                Edges[i][j] = MAX_VALUE;
                if (i == j) Edges[i][j] = 0;
            }
        }
        for (int i = 0; i < E; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            int w = sc.nextInt();
            Edges[u][v] = w;
            Edges[v][u] = w;
        }
    }
}

 

posted @ 2018-03-27 21:06  忧伤的小毛驴  阅读(591)  评论(0编辑  收藏  举报