【发布时间】:2013-04-24 01:49:33
【问题描述】:
我昨天最近发布了一个关于类似问题的问题,但我编写了一些不同的代码,现在遇到了不同的问题。这是导致 StackOverflow 的代码。
** 请注意,3D 网格数组包含超过 100 万个元素,并且可以达到大约 6400 万个元素(存储枚举)。
** 另请注意,这不是无穷大。在小型数据集上,该算法运行良好。
这可能是由极端递归引起的吗?我该如何处理(这是我算法的重要组成部分!)?我已经进行了一些研究,并且听说过使用队列,即使只是大量的 for 循环。
什么会降低导致堆栈溢出的可能性?
谢谢!
/**
* Fills all void cells in the 3D grid of Atom.
*
* @param x
* The starting x coordinate
* @param y
* The starting y coordinate
* @param z
* The starting z coordinate
*/
private void fillAllVoidCells(int x, int y, int z)
{
// Base case -- If not BLOATED_ATOM, BOUNDING_BOX,
// or VOID then must be a cavity (only 4 CellType
// enum types.
if ((grid[x][y][z] == CellType.BLOATED_ATOM)
|| grid[x][y][z] == CellType.BOUNDING_BOX
|| grid[x][y][z] == CellType.VOID)
{
// Pop off runtime stack
return;
}
else
{
// Set to void then check all surrounding cells.
grid[x][y][z] = CellType.VOID;
fillAllVoidCells(x + 1, y, z); // right
fillAllVoidCells(x - 1, y, z); // left
fillAllVoidCells(x, y + 1, z); // in front
fillAllVoidCells(x, y - 1, z); // behind
fillAllVoidCells(x, y, z + 1); // above
fillAllVoidCells(x, y, z - 1); // below
}
}
===== 编辑 ====== 使用堆栈实现的新方法(根据 Roee Gavirel 的帮助) 这会是一个正确的实现吗?
// ----------------------------------------------------------
/**
* Fills all void cells in the 3D grid of Atom.
*
* @param x
* The starting x coordinate
* @param y
* The starting y coordinate
* @param z
* The starting z coordinate
*/
private void fillAllVoidCells(int x, int y, int z)
{
Point p = new Point(x, y, z);
stack.push(p);
while (!stack.isEmpty())
p = stack.top();
stack.pop();
// Base case -- If not BLOATED_ATOM, BOUNDING_BOX,
// or VOID then must be a cavity (only 4 CellType
// enum types.
CellType state = grid[p.x][p.y][p.z];
if ((state == CellType.BLOATED_ATOM) || state == CellType.BOUNDING_BOX
|| state == CellType.VOID)
{
return;
}
else
{
// Set to void then check all surrounding cells.
grid[p.x][p.y][p.z] = CellType.VOID;
Point tempP = p;
tempP.x = p.x - 1;
stack.push(tempP);
tempP.x = p.x + 1;
stack.push(tempP);
tempP.x = p.x; // return to original x coordinate
tempP.y = p.y - 1;
stack.push(tempP);
tempP.y = p.y + 1;
stack.push(tempP);
tempP.y = p.y; // return to original y coordiante
tempP.z = p.z - 1;
stack.push(tempP);
tempP.z = p.z + 1;
stack.push(tempP);
tempP.z = p.z; // return to original z coordinate
}
}
【问题讨论】: