加权/有向图中的第二最短路径

时间:2019-07-15 17:04:21

标签: algorithm dijkstra

我有以下代码。...

边缘:

body {
        background: url(nohisto/media/test.png) no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }

MATRIX: 这段代码获取了我的列表,并从中创建了一个矩阵[] []。

class Edge {
    int src, dest, weight;

    Edge(int src, int dest, int weight) {
        this.src = src;
        this.dest = dest;
        this.weight = weight;
    }
}

肉和土豆:

public static int[][] createMatrix(int vertex, List<Edge> graph) {
    int[][] matrix = new int[vertex + 1][vertex + 1];

    for(int i = 0; i < graph.size(); i++) {
            Edge currentEdge = graph.get(i);
            int startVertex = currentEdge.src;
            int endVertex = currentEdge.dest;
            int weight = currentEdge.weight;
            matrix[startVertex][endVertex] = weight;
    }
    return matrix;
}

迪克斯特拉算法:

    int vertex = 6;
    List<Edge> edges = new ArrayList<Edge>();
    edges.add(new Edge(0, 1, 10));
    edges.add(new Edge(0, 4, 3));
    edges.add(new Edge(1, 2, 5));
    edges.add(new Edge(1, 4, 1));
    edges.add(new Edge(2, 3, 7));
    edges.add(new Edge(2, 4, 8));
    edges.add(new Edge(3, 4, 2));

    int src = 0, dest = 4;

当我执行以下操作static void shortestPath(int[][] adjacencyMatrix, int src, int dest) { int n = adjacencyMatrix[0].length; int[] shortest = new int[n]; boolean[] added = new boolean[n]; for (int v = 0; v < n;v++) { shortest[v] = Integer.MAX_VALUE; added[v] = false; } shortest[src] = 0; int[] parents = new int[n]; parents[src] = NO_PARENT; int v1 = -1; //store temp data int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { for (int v = 0; v < n; v++) { if (!added[v] && shortest[v] < min) { v1 = v; min = shortest[v]; } } added[v1] = true; for (int v = 0; v < n; v++) { int dist = adjacencyMatrix[v1][v]; if (dist > 0 && ((min + dist) <shortest[v])){ parents[v] = v1; shortest[v] = min + dist; } } } dists1.add(shortest[dest]); visitUtil(dest, parents); } static void visitUtil(int i,int[] parents) { if (i == NO_PARENT) return; visitUtil(parents[i], parents); edges1.add(i); } 时,我将得到最短的3。这是有道理的,因为如果我们查看列表,就会发现它。 shortestPath(createMatrix(vertex, edges), src, dest)

为了找到第二条最短路径,这是要运行的路径。

edges.add(new Edge(0, 4, 3));

列表将包含最短的和第二个短的,但第二个最短的未添加。

我希望第二条最短路径是0-1(10),1-4(1),所以11。

为什么?

0 个答案:

没有答案