java - 为什么 Dijkstra 算法对于给定的图不能正常工作?

标签 java algorithm dijkstra

我有以下代码,Dijkstra 算法,是我使用 Wikipedia's article on the algorithm 编写的.

对于给定的图(见图)和起始节点 (1),它返回 5 作为到节点 (4) 的距离,这显然是错误的。但是,当从节点 (4) 出发时,它返回 4 作为到 (1) 的距离,这是正确的。我的代码有什么问题?

Graph

//source = starting point, adj[] = adjacency list
private static int dijkstra (int source, ArrayList<Road>[] adj) {
    HashSet<Integer> vertices = new HashSet<>();

    int[] dist = new int[adj.length];
    int[] prev = new int[adj.length];

    for (int i = 0; i < adj.length; i++) {
        dist[i] = Integer.MAX_VALUE;
        prev[i] = Integer.MAX_VALUE;
        vertices.add(i);
    }

    dist[source] = 0;

    while (!vertices.isEmpty()) {
        int current = Integer.MAX_VALUE;
        for (int v: vertices) {
            if (dist[v] < current) {
                current = v;
            }
        }
        vertices.remove(current);

        for (Road v: adj[current]) {
            int alt = dist[current] + v.distance;

            if (alt < dist[v.end]) {
                dist[v.end] = alt;
                prev[v.end] = current;
            }
        }
    }
}

class Road {
    int end;
    int distance;
}

//This loop builds adjacency list from input such as "1 3 2", where 1 represents
// starting node, 3 represents end node and 2 represents weight of that edge.
//start and end values are decremented in order to be 0-indexed

for (int i = 0; i < M; i++) {
    int start = in.nextInt() - 1;
    int end = in.nextInt() - 1 ;
    int dist = in.nextInt();

    adj[start].add(new Road(end, dist));
    adj[end].add(new Road(start, dist));
}

最佳答案

这段代码导致了错误:

int current = Integer.MAX_VALUE;
for (int v: vertices) {
    if (dist[v] < current) {
        current = v;
    }
}

我假设它应该搜索具有距起始顶点最短路径的未访问节点。但这应该看起来像这样:

int currentPathLen = Integer.MAX_VALUE, current = -1;
for (int v: vertices) {
    if (dist[v] < currentPathLen) {
        current = v;
        currentPathLen = dist[current];
    }
}

关于java - 为什么 Dijkstra 算法对于给定的图不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290898/

相关文章:

java - Spring 依赖注入(inject) : FileNotFound Exception

c - 快速CRC算法?

algorithm - 为什么在这种未定义的情况下,我对 Dijkstra 算法的实现会失败?

algorithm - 网络爬虫算法 : depth?

javascript - cytoscape.js:让 dijkstra 忽略隐藏边缘

java - PriorityQueue 经常需要调整比较器 - 我该如何最好地处理这个问题?

java - 可重复使用的条件/表达式类

Java 反射/泛型

java - Groovy 映射强制生成 <class>_groovyProxy

algorithm - 这个密文和明文之间有什么关系?