繁体   English   中英

在Dijkstra算法中返回路径

[英]Returning the path in Dijkstra's Algorithm

因此,我一直在实现Dijkstra的算法来通过我生成的迷宫进行寻路(我知道你们中的一些人可能会认为像A *这样的东西会更好,但Dijkstra的方法完全适合我的需求),我遇到了一个小问题。 我觉得自己正在忽略某些事情,但是当我从起始节点返回到结束节点的“路径”时,它返回算法采用的整个搜索路径(它访问的每个节点),而不是该节点的路径。

//Uses djikstra's algorithm to find the shortest path between two nodes
//"vertices" is the global ArrayList in the class with all vertices in the graph.
@Override
public ArrayList<Vertex> pathfind(Vertex v1, Vertex v2) {
    ArrayList<Vertex> path = new ArrayList<Vertex>();
    ArrayList<Vertex> unvisited = new ArrayList<Vertex>();
    ArrayList<Vertex> visited = new ArrayList<Vertex>();

    if (!vertices.contains(v1) || !vertices.contains(v2)) {
        return path;
    }

    //initialize distances
    v1.setDistance(0);
    for(Vertex vert : vertices) {
        if(vert != v1) {
            vert.setDistance(Integer.MAX_VALUE);
        }
        unvisited.add(vert);
    }
    Vertex current = v1;

    //begin
    while (!unvisited.isEmpty()) {  
        //for all adjacent vertices that are unvisited
        for (Vertex v : current.adjacentVertices()) {
            if (!visited.contains(v)) {
                //if the distance of that vertex is greater than 
                //the added distance of the current node + the edge connecting the two
                int pathDist = current.getDistance() + findEdge(current, v).getElement(); 
                if (v.getDistance() > pathDist) {
                    //assign the new distance
                    v.setDistance(pathDist);
                }
            }
        }

        //remove the current node from the visited set and add it to visited
        visited.add(current);
        unvisited.remove(current);

        //add current node to the path
        path.add(current);

        //return if we found the destination
        if (current == v2)) {
            return path;
        }

        //else move to the lowest value node
        current = findSmallest(unvisited);

    }
    return path;

}

我知道这一定很痛苦,但我撞到了墙上,任何帮助将不胜感激。 谢谢!

您可能要先计算距离/使用算法将距离稳定到最小值,然后遍历图形以获取路径的节点。

由于current = findSmallest(unvisited)可能会使您从未连接的路径获得节点。

谢谢大家的帮助,我最终制作了一个HashMap,其中包含指向先前节点的链接,并将其遍历到起点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM