【发布时间】:2014-12-18 01:40:51
【问题描述】:
所以,我一直在实施 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.equals(v2)而不是current == v2有什么原因吗?这似乎是您想要==的情况,因为您想查看是否在同一个顶点,而不是顶点中的数据是否相等(如果您覆盖equals)。不过,我怀疑这是造成您问题的原因。 -
@ajb 每个顶点都有一个坐标值,
.equals检查坐标是否相等。你有一个很好的观点,但任何一个都可以。 -
其实,如果
equals已经被Vertex覆盖,那么你就不能使用contains了。 -
糟糕,谢谢!我会纠正的。路径问题仍然存在,可能无关
-
每次将当前添加到已访问路径时,您都会将其添加到路径中。你会想在那里添加一些条件......
标签: java dijkstra path-finding