普利姆算法到迪杰斯特拉算法的转换

3

我正在尝试修改我的Prim算法实现,以便跟踪源节点到其他节点的距离。由于Prim算法和Dijkstra算法几乎相同,所以我无法确定自己哪里出了问题。

我知道问题出在哪里,但是无法解决。

下面是我的代码,请问如何修改它以打印源节点到所有其他节点的最短距离。最短距离存储在名为dist[]的数组中。

代码:

package Graphs;

import java.util.ArrayList;

public class Prims {

    static int no_of_vertices = 0;

    public static void main(String[] args) {
        int[][] graph = {{0, 2, 0, 6, 0},
                {2, 0, 3, 8, 5},
                {0, 3, 0, 0, 7},
                {6, 8, 0, 0, 9},
                {0, 5, 7, 9, 0},
               };
        no_of_vertices = graph.length;
        int [][] result =  new int [no_of_vertices][no_of_vertices];
        boolean[] visited = new boolean[no_of_vertices];
        int dist[] = new int[no_of_vertices];
        for (int i = 0; i < no_of_vertices; i++)
            for (int j = 0; j < no_of_vertices; j++) {
                result[i][j]= 0;
                if (graph[i][j] == 0) {
                    graph[i][j] = Integer.MAX_VALUE;
                }
            }

        for (int i = 0; i < no_of_vertices; i++) {
            visited[i] = false;
            dist[i] = 0;

        }
        ArrayList<String> arr = new ArrayList<String>();
        int min;
        visited[0] = true;
        int counter = 0;
        while (counter < no_of_vertices - 1) {
            min = 999;
            for (int i = 0; i < no_of_vertices; i++) {
                if (visited[i] == true) {
                    for (int j = 0; j < no_of_vertices; j++) {
                        if (!visited[j] && min > graph[i][j]) {
                            min = graph[i][j];
                            dist[i] += min; //  <------ Problem here
                            visited[j] = true;
                            arr.add("Src :" + i + " Destination : " + j
                                    + " Weight : " + min);
                        }
                    }
                }
            }
            counter++;
        }


        for (int i = 0; i < no_of_vertices; i++) {
            System.out.println("Source :  0" + " Destination : " + i
                    + " distance : " + dist[i]);
        }

        for (String str : arr) {
            System.out.println(str);
        }
    }
}

在计算距离数组时存在错误,因为它忘记了将源节点到目标节点的任何中间节点的距离加入其中。

1个回答

2
for (int j = 0; j < no_of_vertices; j++) {
    if (!visited[j] && min > graph[i][j]) {
        min = graph[i][j];
        dist[i] += min; //  <------ Problem here

当然,中间边不会被添加,因为你只添加当前边。你可能需要像这样的内容:
if (dist[i] + graph[i][j] < dist[j])
    dist[j] = dist[i] + graph[i][j];

并且去掉min变量。

虽然你的算法看起来不正确。在每一步中,你应该选择具有最小d[]的节点,并按照我上面写的更新该节点的邻居,然后将其标记为已选并永远不再选择它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接