Dijkstra(樸素)

import java.util.Scanner;

public class Main {

    private static final int INF = Integer.MAX_VALUE;

    /**
     * O(n^2)
     * @param n
     * @param g
     * @return
     */
    public static int dijkstra(int n, int[][] g) {

        boolean[] visited = new boolean[n + 1];

        int[] dist = new int[n + 1];
        for (int i = 1; i <= n; ++ i) {
            dist[i] = INF;
        }
        dist[1] = 0;

        for (int i = 1; i <= n; ++ i) {

            /**
             * 在 未找到最短路徑的點集合中找到最小dist
             */
            int k = -1;
            for (int j = 1; j <= n; ++ j) {
                if (! visited[j] && (k == -1 || dist[k] > dist[j])) {
                    k = j;
                }
            }

            /**
             * 若是最小是INF,則不存在最短路
             */
            if (dist[k] == INF) {
                break;
            }

            visited[k] = true;

            for (int j = 1; j <= n; ++ j) {

                if (g[k][j] != INF && dist[k] + g[k][j] < dist[j]) {
                    dist[j] = dist[k] + g[k][j];
                }
            }
        }

        return dist[n] == INF ? -1 : dist[n];

    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            int n = in.nextInt();
            int m = in.nextInt();

            int[][] g = new int[n + 1][n + 1];

            for (int i = 1; i <= n; ++ i) {
                for (int j = 1; j <= n; ++ j) {
                    g[i][j] = g[j][i] = INF;
                }
            }

            while (m -- > 0) {
                int a = in.nextInt();
                int b = in.nextInt();
                int c = in.nextInt();
                g[a][b] = Math.min(g[a][b], c);
            }

            System.out.println(dijkstra(n, g));

        }
    }
}
相關文章
相關標籤/搜索