2012-09-30 46 views
0

執行此遞歸時收到一個stackoverflow錯誤。 有一個圖案,它說該第一一次:執行遞歸時的Stackoverflow

在MazeGui.move(MazeGui.java:79),這是行,如果(rigting.goal == 真){

和那麼它就會說以下兩個,並且它們在輸出中都會重複很長一段時間。問題發生在這裏的某個地方,我只是不知道是什麼:

在MazeGui.move(MazeGui.java:89)這是招行(rigting.right, POS); //向右移動

在MazeGui.move(MazeGui.java:107)其是線移動(rigting.left, POS); //左移

...

...

我缺少終止條件什麼的,有沒有一些無窮遞歸發生了什麼?我無法把頭圍住它,完全迷失。任何幫助,將不勝感激。

代碼:

public boolean move(Maze rigting, int pos) 
{ 
    if (rigting.goal == true) 
    { 
     return true; 
    } 
    if (rigting.wallR != true) 
    { 
     pos += 1; 
     move(rigting.right, pos); //moves right 

     showLabel(pos); 
     return true; 
    } 
    if(rigting.wallD != true) //checks if there is a wall below 
    { 
     pos += 10; 
     move(rigting.down, pos); //moves down 

     showLabel(pos); 
     return true; 
    } 
    if(rigting.wallL != true) //checks if there is a wall on the left 
    { 
     pos -= 1; 
     move(rigting.left, pos); //moves left 

     showLabel(pos); 
     return true; 
    } 
    if(rigting.wallU != true) //checks if there is a wall above 
    { 
     pos -= 10; 
     move(rigting.up, pos); //moves up 

     showLabel(pos); 
     return true; 
    } 

    return false; 
} 
+0

是的。堆棧溢出通常意味着不滿足停止條件。 – raam86

回答

0

你可能想嘗試這樣的事情,

public boolean move(Maze rigting, int pos) 

{ 
    if (rigting.goal == true) 
    { 
     return true; 
    } 

    if (rigting.wallR != true) 
    { 
     pos += 1; 
     showLabel(pos); 
     return move(rigting.right, pos); //moves right 
    } 

    if(rigting.wallD != true) //checks if there is a wall below 
    { 
     pos += 10; 
     showLabel(pos); 
     return move(rigting.down, pos); //moves down 
    } 
    if(rigting.wallL != true) //checks if there is a wall on the left 
    { 
     pos -= 1; 
     showLabel(pos); 
     return move(rigting.left, pos); //moves left 
    } 

    if(rigting.wallU != true) //checks if there is a wall above 
    { 
     pos -= 10; 
     showLabel(pos); 
     return move(rigting.up, pos); //moves up 
    } 

    return false; 
} 
1

你的 「尋路」 的算法有一個簡單的遞歸循環。

在這種情況下,您的算法會計算出您必須右移。然後,一旦你做完了,它計算你必須向左移動。一旦你向左移動,你就回到了你最後的位置。既然你已經回到了你的起始位置,那麼這個循環會重新開始並且以無限的方式繼續下去(或者直到出現堆棧溢出)。

一個可能的解決方案是分析應用程序的狀態以及狀態更新時的狀態,檢測以前是否處於該狀態;如果你是,相應地修改你的行爲。