我试图用一个自实现的PQ和向量来编码A*算法。它像路口一样眩晕,边缘像道路。我能够正确地编码dijkstra算法,但是我需要提高性能。
目前,我的算法中断抛出空指针异常,如代码中的注释。在过去的5+时间里,我一直在研究算法,同时试图实现它。我并不像dijkstra实现那样完全理解比较路径的方法。
以下是我的当前代码:
private Vertex dijkstra (int start, int end)
{
Vertex current;
while (!(pqOpen.IsEmpty()))
{
current = pqOpen.GetNextItem();
else
{
for (int i = 0; i < current.neighbors.GetNoOfItems(); i++)
{
if (hold != null && hold.neighbors.GetItem(i).fromid != hold.city)
{
int x = 1;
if (hold2 == null || hold.getTentativeDistance() < hold2.getTentativeDistance())
{
hold2.from = hold; //throws null pointer here
hold2.setTentativeDistance(hold.getTentativeDistance());
hold2.setF(hold2.getTentativeDistance() + heuristic(hold2, endLoc));
System.out.println(hold2.from.city);
}
}
}
}
return null;
}
private double heuristic(Vertex goal, Vertex next)
{
return Math.sqrt(Math.pow((goal.x - next.x), 2) + Math.pow((goal.y - next.y), 2));
}我有一种感觉,我完全误解了伪代码,大约在算法的一半,但到目前为止,我还没有找到一个表示,我可以把我的头-所以,有人可能会看我的代码,并指出我的地方和做错了什么?
以下是我用来参考的网站的链接:A.2A
我也尝试过维基百科,但是他们的方法更让我困惑:http://en.wikipedia.org/wiki/A*_search_algorithm
目前,它确实循环了几次,并存储了一些节点,但是它们是不正确的。
编辑:
我已经恢复了我的代码,并尝试了另一种方法。我现在使用这些伪代码示例来理解算法。http://web.mit.edu/eranki/www/tutorials/search/和http://www.redblobgames.com/pathfinding/a-star/introduction.html
在第一个问题上,我认为我的代码是正确的,直到伪代码上的第13行。从那时起,我对他使用的“职位”一词感到困惑。
我注释掉的if语句来自我的dijkstra算法。但是,我认为我前面所表示的伪代码中的if语句应该类似于IF语句。
有人能帮我理解与我的代码相关的伪码第13行吗?
发布于 2015-03-25 20:23:53
我没有读过所有的代码,但是这个部分显然是不好的:)
if (hold2 == null)
{
hold2.from = hold; //throws null pointer here
}看见?如果hold2为null,则尝试向字段from of hold2 (在本例中为null )指定值,因此它将引发异常。
https://stackoverflow.com/questions/29265769
复制相似问题