2016-11-19 47 views
1

我正在解決N皇后,但我有一個問題,由於某種原因,while循環不迭代迭代,tempx和臨時不會由i/j上升。其結果保持輸出0,0N皇后女王是安全的無限循環

public static boolean isSafe(Board board, int row, int col){ 
    int tempx; 
    int tempy; 

    for(int i = -1; i <= 1; i ++){ 
     for(int j = -1; j <= 1; j ++){ 
      try { 
       tempx = row + i; 
       tempy = col + j; 
       while(tempx >= 0 && tempx < board.getRow() && tempy >= 0 && tempy < board.getRow()) { 

        if(board.getTile(tempx, tempy).isOccupied()) 
         return false; 
        tempx += i; 
        tempy += j; 
       } 
      } catch(Exception e){} 
     } 
    } 

    return true; 

} 

編輯: 好吧,我想通了,它似乎做工精細,對於希望在這裏認識的人是這樣,請糾正我,如果有更好的這樣

public static boolean isSafe(Board board, int row, int col){ 
    int tempx; 
    int tempy; 

    for(int i = -1; i <= 1; i ++){ 
     for(int j = -1; j <= 1; j ++){ 
      try { 
       tempx = row + i; 
       tempy = col + j; 
       for(int k = 0; k < board.getRow(); k++){ 
        if(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) { 

         if(board.getTile(tempx, tempy).isOccupied()) 
          return false; 


         tempx += i; 
         tempy += j; 

        } 
       } 


      } catch(Exception e){} 
     } 
    } 

    return true; 

} 
+0

檢查你的第三個while循環的條件,它應該是這樣的**,而((tempx> = 0 && tempx <8)&&(tempy> = 0 && tempy <8) )** –

+0

你真的想在你的'while'循環中使用'||'嗎? – Tom

+0

我試過它仍然給我相同的結果 – shes

回答

0

的方式你是否意識到循環

while(tempx >= 0 || tempx < 8 || tempy >= 0 || tempy < 8) { 

無限號碼tempxtempy它滿意嗎?

你可能想

while(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) {