2013-02-14 20 views
-1

我試圖實現N*N女王算法,有點扭曲它。在這個版本中,女王也可以像騎士一樣在國際象棋中移動。超級女王謎陣列例外

檢查對角線和行似乎很好,但是當我試圖檢查位於遠離我當前位置的「L」位置的女王后,我得到一個「arrayindexoutofboundexception」。 我不完全確定我的check_Knight移動是否正確。我似乎無法找到導致我的代碼中的問題的錯誤。

public class QueenGame { 

    /** 
    * @param args 
    */ 
    static int solution =0; 
    static boolean check_Queen(int row, int col, int queens[]) 
    {  
    for(int i =1; i<col; i++) 
    { 
     if (queens[col-i] == row || 
      queens[col-i] == row-i || 
      queens[col-i] == row+i) 
     { 
     //flag = false; 
     return false; 
     } 

    } 
    return true; 

    } 

    static boolean check_KnightMove(int row, int col, int queens[]) 
    { 
    if(queens[col-2] == (row -1) || queens[col-2] == (row+1)) 
    { 
     return false; 
    } 
    return true; 

    } 

    static void placement(int col, int queens[], int n){ 
    //int solution =0; 
    for (int row = 1; row <= n; row++) { 
     queens[col] = row; 
     if((check_Queen(row,col,queens)) == true) 
     { 
     if((check_KnightMove(row,col,queens)) == true) 
     { 
      if(col == n) 
      { 
      solution++; 
      } 
      else 
      { 
      placement(col+1,queens,n); 
      } 
     } 
     } 
    } 
    queens[col] = 0; 
    } 

    public static void main(String[] args) { 
    int solution =0; 
    Scanner scanner=new Scanner(System.in); 
    //System.out.print("Please enter N"); 
    int n =10; 
    //int n = scanner.nextInt();// TODO Auto-generated method stub 
    //System.out.print(n); 
    int queens[] = new int[n+1]; 
    placement(1,queens,n); 
    System.out.println("nQueens: solution=" + solution); 
    } 

} 
+0

添加額外的檢查,看看你是否已經離開董事會。 – Randy 2013-02-14 23:24:00

+0

你怎麼知道其他皇后的(x,y)位置? – 2013-02-14 23:37:47

+0

@LuiggiMendoza http://en.wikipedia.org/wiki/Eight_queens_puzzle – user1665569 2013-02-14 23:39:45

回答

0

如果col爲0或1,那麼你會得到一個ArrayIndexOutOfBoundsException。在訪問數組之前添加一個檢查。

if ((col >= 2) && (queens[col-2] == (row-1) || queens[col-2] == (row+1))) 
+0

是的,這是發生。儘管如此,我的騎士搜索並不正確。我不認爲它是以L形移動 – user1665569 2013-02-14 23:30:55

+0

這是一個騎士可以移動到當前位置左側的四個位置。您只檢查了(-2,1)和(-2,-1),但(-1,2)和(-1,-2)也是有效的。記住,陣列安全檢查將根據您向左移動的距離而有所不同。 – 2013-02-14 23:51:54

+0

謝謝@MelNicholson。很有幫助 – user1665569 2013-02-15 02:16:09