首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Prims算法到Dijkstra算法

Prims算法到Dijkstra算法
EN

Stack Overflow用户
提问于 2015-04-28 04:41:13
回答 1查看 115关注 0票数 3

我正在尝试使我现有的Prim算法实现,以保持与源代码的跟踪距离。因为prim的算法和Dijkstra的算法几乎相同。我不知道我错过了什么。

我知道问题出在哪里,但我想不出来。

这是我的代码,我如何修改它来打印从源到所有其他顶点的最短距离。最短距离存储在名为dist[]的数组中

代码:

代码语言:javascript
复制
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);
        }
    }
}

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

EN

回答 1

Stack Overflow用户

发布于 2015-04-28 05:19:11

代码语言:javascript
复制
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

当然,中间边不会被添加,因为您只添加了当前边。你可能想要这样的东西:

代码语言:javascript
复制
if (dist[i] + graph[i][j] < dist[j])
    dist[j] = dist[i] + graph[i][j];

并去掉min变量。

尽管你的算法在我看来并不正确。您应该在每个步骤中选择d[]最小的节点,并更新该节点的邻居,如我上面所写的,然后将其标记为已拾取,并且永远不再拾取它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29905551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档