为什么这段代码抛出 StackOverflowError
Why this code throw a StackOverflowError
我想做一种路径查找。然后我使用一个 FIFO 队列从一个单元分配一个距离编号,如果它们有默认编号,则递归地为它们的邻居执行此操作。
在小 space 上它工作正常,但我不明白为什么当我尝试更高 space (100x100) 时它会抛出 WhosebugError。
我的位置 class 只是 (X,Y) 的一个元组。
有人知道哪里出了问题吗?我在想我的 LinkedList 只会浏览整个 space 并停止它。
public class Main {
public static int[][] cells; //[Y][X]
public static LinkedList<Position> modifiedCells = new LinkedList<Position>();
public static void assignNumber(int posX, int posY) {
int currentNumber = cells[posX][posY]+1;
int globalX, globalY;
for (int x = posX-1; x <= posX+1; x++) {
for (int y = posY-1; y <= posY+1; y++) {
if(y>=0 && y< cells[0].length && x>=0 && x<cells.length && cells[x][y] == 0) {
//out of border or still 0.
cells[x][y] = currentNumber;
modifiedCells.addLast(new Position(x,y));
}
}
}
if(modifiedCells.size() > 0){
//take the next cell on list and assign number on neighbors
Position pos = modifiedCells.removeFirst();
assignNumber(pos.getX(),pos.getY());
}
}
public static void main(String[] args) {
cells = new int[100][100];
for (int x = 0; x < 100; x++) {
for (int y = 0; y < 100; y++) {
cells[x][y] = 0;
}
}
assignNumber(50,50);
}
}
默认的最大堆栈(即递归)深度为 1000。100 x 100 将导致深度为 10000。
一些算法(例如这个算法)无法随着问题 space 的增长而很好地扩展。
要使其正常工作,您可以尝试设置更大的堆栈大小:
java -Xss1G com.mypackage.Main
我想做一种路径查找。然后我使用一个 FIFO 队列从一个单元分配一个距离编号,如果它们有默认编号,则递归地为它们的邻居执行此操作。
在小 space 上它工作正常,但我不明白为什么当我尝试更高 space (100x100) 时它会抛出 WhosebugError。
我的位置 class 只是 (X,Y) 的一个元组。
有人知道哪里出了问题吗?我在想我的 LinkedList 只会浏览整个 space 并停止它。
public class Main {
public static int[][] cells; //[Y][X]
public static LinkedList<Position> modifiedCells = new LinkedList<Position>();
public static void assignNumber(int posX, int posY) {
int currentNumber = cells[posX][posY]+1;
int globalX, globalY;
for (int x = posX-1; x <= posX+1; x++) {
for (int y = posY-1; y <= posY+1; y++) {
if(y>=0 && y< cells[0].length && x>=0 && x<cells.length && cells[x][y] == 0) {
//out of border or still 0.
cells[x][y] = currentNumber;
modifiedCells.addLast(new Position(x,y));
}
}
}
if(modifiedCells.size() > 0){
//take the next cell on list and assign number on neighbors
Position pos = modifiedCells.removeFirst();
assignNumber(pos.getX(),pos.getY());
}
}
public static void main(String[] args) {
cells = new int[100][100];
for (int x = 0; x < 100; x++) {
for (int y = 0; y < 100; y++) {
cells[x][y] = 0;
}
}
assignNumber(50,50);
}
}
默认的最大堆栈(即递归)深度为 1000。100 x 100 将导致深度为 10000。
一些算法(例如这个算法)无法随着问题 space 的增长而很好地扩展。
要使其正常工作,您可以尝试设置更大的堆栈大小:
java -Xss1G com.mypackage.Main