2017-05-15 70 views
0

我有一類就是解決一個迷宮(矩陣),這是很簡單的一個項目,然而我在與if語句應該驗證一些麻煩矩陣單元的可用性,看看這個數字是否是路徑的一部分。如果聲明關於基質細胞沒有返回true(JAVA)

這裏的測試迷宮我已經創建:

// 0 = start 
    // 1 = path 
    // 2 = wall 
    // 3 = end 
    // 5 = tried 
    // 6 = final path 

int [][] maze = {{2,2,2,0,2,2,2,2,2,2}, 
       {2,2,2,1,2,2,1,1,1,2}, 
       {2,2,2,1,2,2,2,2,1,2}, 
       {2,2,2,1,2,2,2,1,1,2}, 
       {2,2,1,1,2,2,1,2,1,1}, 
       {2,1,1,0,2,2,2,2,2,2}, 
       {2,1,2,0,2,2,2,2,2,2}, 
       {2,1,1,0,2,2,2,2,2,2}, 
       {2,2,3,0,2,2,2,2,2,2},}; 

這裏是檢查是否當前單元格是有效的行走方法:

private boolean valid (int row, int column) { 

    boolean result = false; 

    // checks if cell is inside of the matrix 
    if (row >= 0 && row < maze.length && 
      column >= 0 && column < maze[0].length) { 

     // checks if cell is not blocked, if it has previously been tried or it's the end 
     if (maze[row][column] == 1 || maze[row][column] == 3 || maze[row][column] == 0 || maze[row][column] == 5) { 
      result = true; 
     }else{ 

      result = false; 
     } 
    } 

    return result; 

} 

從使用打印語句我我發現這個問題可能在嵌套的if語句中。但可能還有另一個問題,我不確定,這是解決方法。

public boolean solve(int row, int column) { 

    boolean solved = false; 

    if (valid(row, column)) { 

     maze[row][column] = 5; 

     if (maze[row][column] == 1 || maze[row][column] == 0){ 
      if(!solved){//it's going to call the function it self and move if possible. 
       solved = solve(row + 1, column); // South 
       if (!solved) 
        solved = solve(row, column + 1); // East 
       if (!solved) 
        solved = solve(row - 1, column); // North 
       if (!solved) 
        solved = solve(row, column - 1); // West 
      } 
      if (solved) // part of the final path 
       maze[row][column] = 7; 
     }else if (maze[row][column] == 3) { 
      solved = true; 
      System.out.println("lol the end"); 
     } 
     //exception here not to leave the maze and case there's no 0 
    } 
    return solved; 
} 
+0

這就是爲什麼調試器存在。我會花一些時間學習如何使用IDE的調試器。 – OldProgrammer

+0

好,這一個時間進行比較,如果不是一切是真實的,它會返回false – Stultuske

+0

我沒有測試過,但是,當你調用該行'迷宮[行] [列] = 5;'然後當你達到這個如果:!'如果(迷宮[行] [列] == 1 ||迷宮[行] [列] == 0){'它總是假...('如果(5 = 0 OR 5 = 1)',這就是它說的)或者我錯過了什麼......? – Frakcool

回答

0

把聲明

maze[row][column] = 5; 

只是下一個(if)語句後:

if (maze[row][column] == 1 || maze[row][column] == 0){ 

,因爲它保護正確評價這一if語句中的條件。

+0

我試過了,但它仍然無法工作 –