zoukankan      html  css  js  c++  java
  • 算法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();
            }
        }
    }
    
    
    
  • 相关阅读:
    剑指Offer
    剑指Offer
    剑指Offer
    面积(area)
    最少步数
    细胞
    集合的前N个元素
    1~100卡特兰数(存一下hhhh)
    [Codeforces137C]History(排序,水题)
    [Codeforces676B]Pyramid of Glasses(递推,DP)
  • 原文地址:https://www.cnblogs.com/impw/p/15542460.html
Copyright © 2011-2022 走看看