所以,我一直在实施Dijkstra的算法,通过我生成的迷宫进行寻路(我知道你们中的一些人可能认为像A *这样的东西会更好,但是Dijkstra完全适合我的需要),我遇到了一个小问题。我觉得我忽略了某些东西,但是当我回到“路径”时#34;从起始节点到结束节点,它返回算法采用的整个搜索路径(它访问的每个节点),而不是节点的路径。
//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;
}
我知道这肯定是一件非常明显的事情,但是我的头靠在墙上,任何帮助都会受到赞赏。谢谢!
答案 0 :(得分:1)
您可能希望先使用算法计算距离/将距离稳定到最小值,然后在图表上运行以获取路径的节点。
由于current = findSmallest(unvisited)
可能会从未连接的路径获取节点。
答案 1 :(得分:1)
感谢大家的帮助,我最终创建了一个HashMap,其中包含指向前一个节点的链接,并将其遍历到开头。