[英]StackOverflow on Recursive Function
我有以下功能,該功能應該產生我可以在n步中從原點到達的笛卡爾平面中的所有坐標:
原點是“位置”,步數是“強度”,它是整數1-10。 但是,我不斷收到stackoverflow錯誤。 每次調用它時,我都會在ArrayList位置上調用clear。 有什么想法嗎?
更新的代碼:
// Returns all positions reachable in 'strength' steps
public ArrayList<Int2D> findEscapeSpace(Int2D location, Field f) {
// Are we still within the given radius?
if((Math.abs(location.getX() - this.location.getX()) + Math.abs(location.getY() - this.location.getY())) < strength) {
System.out.println("Starting on " + location);
// If this position is not contained already, and if it doesn't contain a wall
if(!positions.contains(location) && f.wallField.getObjectsAtLocation(location) == null) {
positions.add(location);
System.out.println("added " + location);
}
// Getting neighboring positions
ArrayList<Int2D> neigh = findNeighPos(location, f);
for(Int2D pos : neigh) {
System.out.println("looking into " + pos + " at depth " + (Math.abs(location.getX() - this.location.getX()) + Math.abs(location.getY() - this.location.getY())) + " and strength " + strength);
if(!positions.contains(pos))
findEscapeSpace(pos, f);
}
}
System.out.println(positions.size());
return positions;
}
舊代碼
public ArrayList<Int2D> positions = new ArrayList<Int2D>();
// Returns all positions reachable in 'strength' steps
public ArrayList<Int2D> findEscapeSpace(Int2D location, Field f) {
// Are we still within the given radius?
if((Math.abs(location.getX() - this.location.getX()) + Math.abs(location.getY() - this.location.getY())) < strength) {
// If this position is not contained already, and if it doesn't contain a wall
if(!positions.contains(location) && f.wallField.getObjectsAtLocation(location) == null)
positions.add(location);
// Getting neighboring positions
ArrayList<Int2D> neigh = findNeighPos(location, f);
for(Int2D pos : neigh) {
findEscapeSpace(pos, f);
}
}
return positions;
}
public ArrayList<Int2D> findNeighPos(Int2D currentP, Field f) {
ArrayList neighPositions = new ArrayList<Int2D>();
int cx = currentP.getX();
int cy = currentP.getY();
int maxY = f.HEIGHT-1;
int maxX = f.WIDTH-1;
// A few checks to make sure we're not going off tack (literally)
if(cx > 0 && cy < maxY)
neighPositions.add(new Int2D(cx-1, cy+1));
if(cy < maxY)
neighPositions.add(new Int2D(cx, cy+1));
if(cx < maxX && cy < maxY)
neighPositions.add(new Int2D(cx+1, cy+1));
if(cx > 0)
neighPositions.add(new Int2D(cx-1, cy));
if(cx < maxX)
neighPositions.add(new Int2D(cx+1, cy));
if(cx > 0 && cy > 0)
neighPositions.add(new Int2D(cx-1, cy-1));
if(cy > 0)
neighPositions.add(new Int2D(cx, cy-1));
if(cx < maxX && cy > 0)
neighPositions.add(new Int2D(cx+1, cy-1));
return neighPositions;
}
您的遞歸似乎沒有終止條件。 看起來您可能想要將strength
作為參數傳遞給findEscapeSpace()
,並且當該方法遞歸使它傳遞的值比傳遞給它的值小一個時。
除此之外,您的算法看起來效率很低,因為它可能會多次生成並測試許多可到達的單元,此外,檢查每個單元是否已被發現的成本也相對較高。 但這是下一個要克服的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.