过去几个小时我一直被困在这个棘手的错误上,我想知道这里是否有人可以帮助我。
基本上我通过递归实现A *,并且我希望每个节点(在代码中称为tile)存储它已经通过的先前节点数的整数值。这样,一旦算法找到了退出,它就可以返回并返回最短的路径。
然而,每次循环通过该功能时,转向计数器都会被重置。但是,如果我删除该行:
map[y][x].setID(path);
它很好,但当然会产生堆栈溢出错误,但我真的不明白为什么会导致这个问题。
代码的主要部分在这里:
private static Tile[][] findSquares(IntVector v, Tile[][] map, int wall, int empty, int end, int start, int path, int turns)
{
// System.out.println(turns);
if (!isHit)
{
for (int y = v.y - 1; y <= v.y + 1; y++)
{
for (int x = v.x - 1; x <= v.x + 1; x++)
{
if (map[y][x].id == end)
{
isHit = true;
}
else if (map[y][x].id != wall && map[y][x].id != path && map[y][x].id != end && !isHit && map[y][x].id != start)
{
map[y][x].turns++;
System.out.println(map[y][x].turns); //Always Results in 1
map[y][x].setID(path);
findSquares(new IntVector(x, y), map, wall, empty, end, start, path, turns);
break;
}
}
}
}
return map;
}
使用代表节点的tile。这是tile类:
static private class Tile
{
int id;
int turns = 0;
Tile(int id)
{
this.id = id;
}
public void addTurn()
{
turns++;
}
public void setID(int id)
{
this.id = id;
}
public int getTurns()
{
return turns;
}
public Tile setTurns(int turns)
{
this.turns = turns;
return this;
}
}
也许是因为tile类是静态的?
答案 0 :(得分:0)
问题不在于转弯计数器正在“重置”,而是你永远不会多次递增它。 turns
增加的分支仅在id != path
时出现,但您之后立即将id
设置为path
,因此它永远不会再增加。
你可能想要的是什么
map[y][x].turns = map[v.y][v.x].turns + 1;
无论如何,即使你修正了距离计算,你的代码也几乎不像A *。看起来你的代码实际上正在做的是深度优先搜索,在程序调用堆栈中隐式维护你的搜索堆栈。
A *算法涉及维护要搜索的节点的优先级队列,并使用启发式函数加当前距离来计算插入节点的新优先级。