package com.thinker.suanfa.dongtai;

/**
 * @author lzh
 */
public class Dijkstra {
    private final int max = Integer.MAX_VALUE;
    private int[][] arr ; // 邻接矩阵
    private String[] edges;//边界
    private boolean[] visited;// 访问过的节点，false表示没有访问过
    private int size;
    private int v0 = 0;

    /**
     * init
     */
    public void init(){
        arr = new int[][]{
                {0 ,7 ,9 ,0 ,0 ,14},
                {7 ,0 ,10,15,0 ,0 },
                {9 ,10,0 ,11,0 ,2 },
                {0 ,15,11,0 ,6 ,0 },
                {0 ,0 ,0 ,6 ,0 ,9 },
                {14,0 ,2 ,0 ,9 ,0 }
        };
        edges = new String[]{"a","b","c","d","e","f"};
        size = edges.length;
        visited = new boolean[size];
        for(int i=0;i<size;i++){
            for(int j=0;j<size;j++){
                if(arr[i][j] == 0) arr[i][j] = max;
            }
        }
    }

    /**
     *
     * @param end 求最短路径
     * @return 最短路径
     *
     */
    private int dijkstra(int end){
        int[] dist = new int[size];//最短路径
        int[] path = new int[size];//经过的路径
        //初始化
        for(int i=0;i<size;i++){
            dist[i] = arr[v0][i];//假设两个节点之间的直接距离最短
            visited[i] = false;
            if(i != v0 && dist[i] < max) path[i] = v0;
            else path[i] = -1;
        }
        visited[v0] = true;
        int min ;
        int v = 0;//保存下一个最近节点的下标
        for(int i=1;i<size;i++){
            min = max;//
            //求得最近的下一个没有访问过的节点
            for(int j=0;j<size;j++){
                if(!visited[j] && dist[j] < min){
                    v = j; min = dist[j];
                }
            }
            visited[v] = true;
            //重新计算最短路径
            for(int j=0;j<size;j++){
                if(!visited[j] && arr[v][j] < max){
                    if((min + arr[v][j]) <= dist[j]){
                        dist[j] = min + arr[v][j];
                        path[j] = v;
                    }
                }
            }
        }
        return dist[end];
    }

    public static void main(String[] args) {
        Dijkstra dijkstra = new Dijkstra();
        dijkstra.init();
        System.out.println(dijkstra.dijkstra(4));
    }
}
