gpt4 book ai didi

c# - A* 算法 System.StackOverflowException

转载 作者:行者123 更新时间:2023-11-30 12:33:03 25 4
gpt4 key购买 nike

public List<Location2D> Path(Location2D start, Location2D goal)
{
openset = new List<NodeInfo>(); // The set of tentative nodes to be evaluated, initially containing the start node.
closedset = new List<NodeInfo>(); // The set of nodes already evaluated.
path = new List<Location2D>(); // The path result.
came_from = new Dictionary<Location2D, Location2D>();

NodeInfo Start = new NodeInfo();
Start.SetLoction(start.X, start.Y);
Start.H = GetHValue(start, goal);
openset.Add(Start);

while (openset.Count > 0) { // while openset is not empty
NodeInfo current = CheckBestNode(); //the node in openset having the lowest f_score[] value

if (current.Location.Equals(goal)) {
ReconstructPathRecursive(current.Location);
return path;
}

for (int i = 0; i < 8; i++) { // neighbor nodes.
NodeInfo neighbor = new NodeInfo();
neighbor.SetLoction((ushort)(current.Location.X + ArrayX[i]), (ushort)(current.Location.Y + ArrayY[i]));

bool tentative_is_better = false;

if (closedset.Contains(neighbor))
continue;
if (!map.Cells[neighbor.Location.X, neighbor.Location.Y].Walkable) { closedset.Add(neighbor); continue; }

Double tentative_g_score = current.G + DistanceBetween(current.Location, neighbor.Location);

if (!openset.Contains(neighbor)) {
openset.Add(neighbor);
neighbor.H = GetHValue(neighbor.Location, goal);
tentative_is_better = true;
} else if (tentative_g_score < neighbor.G) {
tentative_is_better = true;
} else {
tentative_is_better = false;
}

if (tentative_is_better) {
came_from[neighbor.Location] = current.Location;
neighbor.G = tentative_g_score;
}
}
}
return null;
}

private void ReconstructPathRecursive(Location2D current_node)
{
Location2D temp;
if (came_from.TryGetValue(current_node, out temp)) {
path.Add(temp);
ReconstructPathRecursive(temp);
} else {
path.Add(current_node);
}
}

我正在实现 A* 算法,当它找到目标时,它会转到 ReconstructPathRecursive然后应用程序崩溃并抛出此异常 在 mscorlib.dll 中发生类型为“System.StackOverflowException”的未处理异常

此线程停止时调用堆栈上只有外部代码帧。外部代码框架通常来自框架代码,但也可以包括在目标进程中加载​​的其他优化模块。

我知道怎么了!

最佳答案

它实际上不必是递归的,因为它是尾递归的。所以你可以这样重写它:

private void ReconstructPathIterative(Location2D current_node)
{
Location2D temp;
while (came_from.TryGetValue(current_node, out temp))
{
path.Add(temp);
current_node = temp;
}
path.Add(current_node);
}

这仅在路径太长无法放入堆栈时才有用,如果它是无限的则无济于事。

关于c# - A* 算法 System.StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10079000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com