Dijkstra算法和Floyd算法

正好实验课遇到,就重温一下这两个算法吧。

测试用例都是简单的一个7个点的例题。

1.Dijkstra

import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

public class dij {
    static int M = Integer.MAX_VALUE/2;
    class point implements Comparable<point>{
        int num;
        int path;
        public point(int a, int b){
            this.num = a;
            this.path = b;
        }

        public int compareTo(point p) {
            return this.path - p.path;
        }
    }

    public int dijkstra(int[][] e, int st, int en) {

        PriorityQueue<point> pq = new PriorityQueue<point>();
        Set<Integer> set = new HashSet<Integer>();
        int len = e.length;
        pq.offer(new point(st, 0));
        while(!pq.isEmpty()) {
            point cur = pq.poll();
            set.add(cur.num);
            if(cur.num == en) return cur.path;
            int[] c = e[cur.num];
            for(int i = 0; i < len; i++) {
                if(set.contains(i)) continue;
                pq.offer(new point(i, cur.path + c[i]));
            }

        }

        return -1;
    }

    public static void main(String[] args) {
        int[][] e = new int[][] {{0,1,2,3,M,M,M}, {1,0,M,M,M,6,M}, {2,M,0,M,5,4,M},{3,M,M,0,4,M,M},{M,M,5,4,0,M,7},{M,6,4,M,M,0,8},{M,M,M,M,7,8,0}};
        dij di = new dij();
        int[][] ans = new int[7][7];

        for (int i = 0; i < e.length; i++) {
            for (int j = 0; j < e.length; j++) {
                ans[i][j] = di.dijkstra(e, i, j);
            }
        }
        for (int[] an :
                ans) {
            System.out.println(Arrays.toString(an));
        }

    }
}

输出结果如下:

2.Floyd

import java.util.Arrays;

public class floyd {
    static int M = Integer.MAX_VALUE/2;
    void floy (int[][] e) {

        int len = e.length;

        for(int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                for (int k = 0; k < len; k++) {
                    e[j][k] = Math.min(e[j][k], e[j][i] + e[i][k]);
                }
            }
        }

    }

    public static void main(String[] args) {
        int[][] e = new int[][]{{0, 1, 2, 3, M, M, M}, {1, 0, M, M, M, 6, M}, {2, M, 0, M, 5, 4, M}, {3, M, M, 0, 4, M, M}, {M, M, 5, 4, 0, M, 7}, {M, 6, 4, M, M, 0, 8}, {M, M, M, M, 7, 8, 0}};
        new floyd().floy(e);
        for (int[] an :
                e) {
            System.out.println(Arrays.toString(an));
        }

    }
}

输出结果如下图:

img

原文地址:https://www.cnblogs.com/agnes6/p/13940460.html