算法17 《啊哈算法》第六章 Dijkstra 算法一~通过边实现松弛 java

main

  1. 找到最近(路程最短)节点————如有连接到其他节点最短路径,必通过最近节点
  2. 然后比较通过该中间节点与不经过的路径,取最小值
  3. 重复12(取过的节点不再取)

题目


求每个节点到其他节点最小值

代码&结果

结果

起始二维数组

 0  1 12 99 99 99
99  0  9  3 99 99
99 99  0 99  5 99
99 99  4  0 13 15
99 99 99 99  0  4
99 99 99 99 99  0

codes

class Main {
    int [][]e=new int[][]{{ 0, 1,12,99,99,99}
                         ,{99, 0, 9, 3,99,99}
                         ,{99,99, 0,99, 5,99}
                         ,{99,99, 4, 0,13,15}
                         ,{99,99,99,99, 0, 4}
                         ,{99,99,99,99,99, 0}};
    int[][]mark=new int[6][6];
    public static void main(String[] args) {
        dj a=new dj();
        a.dijkstra();
    }

    public  void dijkstra() {
        int th_n = 0, th = 99;
        for (int first = 0; first < 6; first++) {
            for (int r = 0; r < 5; r++) {
                for (int i = 0; i < 6; i++) {//最近节点
                    if (e[first][i] > 0 && e[first][i] < th && mark[first][i] != 1) {
                        th = e[first][i];
                        th_n = i;
                    }
                }
                mark[first][th_n] = 1;//标记!!!!!!!!!!!!!!!30mins

                for (int i = 0; i < 6; i++) {//更新距离
                    if (e[th_n][i] != 99 && e[th_n][i] != 0) {//最近出点
                        if (e[first][i] > e[first][th_n] + e[th_n][i]) {//更新
                            e[first][i] = e[first][th_n] + e[th_n][i];
                        }
                    }
                }


                th = 999;//restart
            }
            


        }
//打印结果
        for (int y=0;y<6;y++){
            for (int x=0;x<6;x++) System.out.print(e[y][x]+" ");
            System.out.println();
        }
    }
}


原文地址:https://www.cnblogs.com/impw/p/15542460.html