java Dijkstra 實現

參考

https://blog.csdn.net/heroacool/article/details/51014824

https://www.cnblogs.com/mingjiatang/p/5974451.html

https://www.jianshu.com/p/ff6db00ad866

我這實現是有向圖,無向圖,可自行實現

實現

 

public class Dijkstra {

    static int[][] source = {
            {-1, -1, 10, -1, 30, 100},
            {-1, -1, 5, -1, -1, -1},
            {-1, -1, -1, 50, -1, -1},
            {-1, -1, -1, -1, -1, 10},
            {-1, -1, -1, 20, -1, 60},
            {-1, -1, -1, -1, -1, -1},
    };

    public static String getMinDistance() {

        Iterator<Map.Entry<String, Integer>> iterator = Umap.entrySet().iterator();
        Map.Entry<String, Integer> minEntry = null;

        while (iterator.hasNext()) {
            Map.Entry<String, Integer> itempEntry = iterator.next();
            if (minEntry == null || itempEntry.getValue() < minEntry.getValue()) {
                minEntry = itempEntry;
            }
        }
        //    數據清空
        Umap.clear();
        Smap.put(minEntry.getKey(), minEntry.getValue());
        System.out.println(minEntry.toString());
        return minEntry.getKey();
    }

    //    u查找s數據
    public static boolean find() {
        if (sList.isEmpty()) {
            sList.add(0);
        }
        for (int i = 0; i < sList.size(); i++) {
            for (int j = 0; j < source.length; j++) {
                String key = sList.get(i) + "->" + j;
                String Rkey = j + "->" + sList.get(i);
                if (source[sList.get(i)][j] != -1 && !(userPort.contains(key) || userPort.contains(Rkey))) {
                    Umap.put(key, source[sList.get(i)][j]);
                }
            }
        }
        System.out.println(Umap.toString());
        String[] minIndex = getMinDistance().split("->");
        System.out.println(Arrays.toString(sList.toArray()));
        if (sList.contains(Integer.parseInt(minIndex[1]))) {
            return false;
        } else {
            userPort.add(minIndex[0] + "->" + minIndex[1]);
            userPort.add(minIndex[1] + "->" + minIndex[0]);
            sList.add(Integer.parseInt(minIndex[1]));
            return true;
        }
    }
    //    最後的結果
    public static Map<String, Integer> Smap = new HashMap<>();
    //    S到U的所有地距離
    public static Map<String, Integer> Umap = new HashMap<>();
    //已經使用的數據
    public static List<Integer> sList = new ArrayList<>();
    //    已使用座標
    public static List<String> userPort = new ArrayList<>();


    public static void main(String[] args) {
        boolean flag = true;
        while (flag) {
            flag = find();
            System.out.println();
        }
    }
}

輸出結果

1 s集合

2,s集合最小值

3,u集合

{0->5=100, 0->4=30, 0->2=10}
0->2=10
[0]

{0->5=100, 0->4=30, 2->3=50}
0->4=30
[0, 2]

{0->5=100, 4->3=20, 2->3=50, 4->5=60}
4->3=20
[0, 2, 4]

{0->5=100, 3->5=10, 2->3=50, 4->5=60}
3->5=10
[0, 2, 4, 3]

{0->5=100, 2->3=50, 4->5=60}
2->3=50
[0, 2, 4, 3, 5]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章