2015-04-29 58 views
0

我正在使用什麼是深度優先搜索來解決迷宮使用我自己的堆棧創建的類作業。我相信我得到這個錯誤的原因是因爲我的程序從未滿足finishSpot的條件。我已經使用了調試器,它看起來像是無限地停留在finishSpot之前的Point處。我的邏輯似乎大部分是正確的,除非我的迷宮求解器試圖完成迷宮,所以我只需要幫助滿足導致我的程序崩潰的最後一個條件。搜索算法導致StackOverFlowError

這是一個示例迷宮,其中's'開始,'f'結束,'*'是牆。

***** 
*s* * 
* * * 
* f* 
***** 

這是我的主要使用我的LinkedStack類,我可以發佈如果需要。

//Creates a Stack and determines the start and endpoints. 
public static void solveDFS(char [][] maze){ 
    LinkedStack stack = new LinkedStack(); 
    Point currentSpot = findPoint(maze,'s'); 
    Point finishSpot = findPoint(maze, 'f'); 
    findPath(maze,currentSpot, finishSpot,stack); 
} 
//Finds a point by searching for a char. 
private static Point findPoint(char [][] maze, char c) { 
    for (int i = 0; i < maze.length; i++) { 
     for (int j = 0; j < maze[i].length; j++) { 
      if (maze[i][j] == c) { 
       return new Point(i, j); 
      } 
     } 
    } 
    return null; 
} 
//Search algorithm looks for all neighbor locations 
private static boolean findPath(char [][] maze, Point currentSpot, Point finishSpot, LinkedStack stack){ 
    boolean hasSolution = false; 
    stack.push(currentSpot); 

    while(currentSpot != finishSpot && !stack.isEmpty()){ 
     // Checks Right 
     if(currentSpot.x < maze.length){ 
      if(maze[currentSpot.x + 1][currentSpot.y] == ' '){ 
       stack.push(new Point(currentSpot.x + 1, currentSpot.y)); 
      } 
     } 
     // Checks Left 
     if(currentSpot.x > 0){ 
      if(maze[currentSpot.x - 1][currentSpot.y] == ' '){ 
       stack.push(new Point(currentSpot.x - 1, currentSpot.y)); 
      } 
     } 
     // Checks Up 
     if(currentSpot.y > 0){ 
      if(maze[currentSpot.x][currentSpot.y - 1] == ' '){ 
       stack.push(new Point(currentSpot.x, currentSpot.y - 1)); 
      } 
     } 
     // Checks Down 
     if(currentSpot.y < maze[currentSpot.x].length){ 
      if(maze[currentSpot.x][currentSpot.y + 1] == ' '){ 
       stack.push(new Point(currentSpot.x, currentSpot.y + 1)); 
      } 
     } 
     // Checks Finish (My program never meets this condition help!) 
     if(currentSpot == finishSpot){ 
      printMaze(maze); 
      hasSolution = true; 
     } 
     currentSpot = stack.pop(); 
     findPath(maze, currentSpot, finishSpot, stack); 
    } 
    return hasSolution; 
} 
+0

'如果(currentSpot == finishSpot)'...我不認爲你應該使用''==這裏。改用'if(currentSpot.equals(finishSpot))'並在'Point'類中覆蓋'equals'和'hashCode'。 – Tom

+1

爲什麼要使用堆棧而不是遞歸? – mangusta

+0

@mangusta這是我需要這樣做的任務。 – JCCS

回答

0

以下條件將永遠不會在你的代碼

while(currentSpot != finishSpot && !stack.isEmpty()){ 
    ... 
    if(currentSpot == finishSpot){ 
0

我不認爲你可以比較Points變量一樣,是在同一時間如此。 嘗試覆蓋的方法equals

this question